从 Python 用户处获取矩阵输入
在本教程中,我们将学习如何从 Python 用户处获取矩阵输入。我们可以通过两种不同的方式从用户处获取输入。让我们来看一下这两种方式。
方法 1
从用户处逐个获取矩阵的所有数字。请参阅以下代码。
示例
# initializing an empty matrix matrix = [] # taking 2x2 matrix from the user for i in range(2): # empty row row = [] for j in range(2): # asking the user to input the number # converts the input to int as the default one is string element = int(input()) # appending the element to the 'row' row.append(element) # appending the 'row' to the 'matrix' matrix.append(row) # printing the matrix print(matrix)
输出
如果您运行以上代码,则会得到以下结果。
1 2 3 4 [[1, 2], [3, 4]]
矩阵 2
一次获取一行带有空格分隔的值。并使用 map 和 int 函数将它们转换为。请参阅代码。
示例
# initializing an empty matrix matrix = [] # taking 2x2 matrix from the user for i in range(2): # taking row input from the user row = list(map(int, input().split())) # appending the 'row' to the 'matrix' matrix.append(row) # printing the matrix print(matrix)
输出
如果您运行以上代码,则会得到以下结果。
1 2 3 4 [[1, 2], [3, 4]]
结论
如果您对教程有任何疑问,请在评论区中提及。
广告宣传
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP