使用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]]
结论
如果您在本教程中有疑问,请在评论部分中提及它们。
热门推荐
4 初八的祝福语简短
6 孙媳妇祝福语简短
10 新年的祝福语简短的
11 生日油画棒祝福语简短
12 生日哥哥祝福语简短独特
13 麻辣拌店祝福语简短
14 前程祝福语简短暖心
15 班级群毕业祝福语简短
16 老板生日祝福语简短语
17 生日祝福语简短而有深意
18 新年祝同学祝福语简短