我编写了一个程序来打印 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]] 但我和# 39;我正在寻找一种更有效的方法。
请注意,我不建议使用numpy和其他内置库。
感谢您的帮助。
答案 0 :(得分:0)
以下是其他方式的几个例子。我不确定第一个例子是你在寻找什么,但我把它扔进去玩!
>>> userin = '1 2'.split()
... userin2 = '3 4'.split()
... userin3 = '5 6'.split()
... userin4 = '7 8'.split()
>>> print('[[{}, {}], [{}, {}]]'.format(*userin, *userin2))
... print('[[{}, {}], [{}, {}]]'.format(*userin3, *userin4))
[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
>>> print([[int(a) for a in pair] for pair in (userin, userin2)])
... print([[int(a) for a in pair] for pair in (userin3, userin4)])
[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
答案 1 :(得分:0)
我就是这样做的:
Enter first two digit for first 2x2 matrix: 1 2
Enter last two digit for first 2x2 matrix: 3 4
Enter first two digit for second 2x2 matrix: 5 6
Enter last two digit for second 2x2 matrix: 7 8
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
如果它总是只是那4个输入语句,我认为这很好。如果输入是可变的,那么使函数更有意义。
输出:
@Value("#{${validators}}")
private Map<String,String> validators;
答案 2 :(得分:0)
为什么不放入while循环来获取任意数量的矩阵,为什么不一次接收所有4个元素呢?
类似的东西:
user_in = ['0']
matrices = []
while (user_in[0].lower() != 'q'):
user_in = input("Input 2x2 matrix(space separated), enter 'q' to quit: ").split(' ')
if len(user_in) == 4:
a, b, c, d = user_in
m2x2 = [[int(a), int(b)], [int(c), int(d)]]
matrices.append(m2x2)
for matrix in matrices:
print(matrix)