【发布时间】:2018-03-03 02:59:40
【问题描述】:
我编写了一个程序来打印一个 2x2 矩阵,其中每个矩阵中表示的数字是通过用户输入给出的。
例如:
userin = 1 2 #two digit input with a spacing in between
userin2 = 3 4 #userin and userin2 is first matrix
userin3 = 5 6
userin4 = 7 8 #userin3 and userin4 is second matrix
The program would then print out: [[1,2],[3,4]], #first matrix
[[5,6],[7,8]] #second matrix
我让程序按我的意愿工作,但我觉得我编写的代码效率太低,以至于我创建了太多空列表来满足用户输入。
userin = input("Enter first two digit for first 2x2 matrix: ").split(' ')
userin2 = input("Enter last two digit for first 2x2 matrix: ").split(' ')
userin3 = input("Enter first two digit for second 2x2 matrix: ").split(' ')
userin4 = input("Enter last two digit for second 2x2 matrix: ").split(' ')
lst1 = []
lst2 = []
lst3 = []
lst4 = []
matrix = []
matrix2 = []
for x in userin:
x = int(x)
lst1.append(x)
for j in userin2:
j = int(j)
lst2.append(j)
for x in userin3:
x = int(x)
lst3.append(x)
for j in userin4:
j = int(j)
lst4.append(j)
matrix.append(lst1)
matrix.append(lst2)
matrix2.append(lst3)
matrix2.append(lst4)
print(matrix)
print(matrix2)
程序以我想要的格式输出 [[1,2],[3,4]],[[5,6],[7,8]] 但我'我正在寻找一种更有效的方法。
请注意,不建议我使用 numpy 和其他内置库。
感谢您的帮助。
【问题讨论】:
-
这个问题更适合代码审查:codereview.stackexchange.com
-
查找列表理解并注意 string.split 返回一个列表