4 回答
TA贡献1793条经验 获得超6个赞
现在,您的代码分别要求每个元素。如果你输入数字直到它像这样结束
111
222
333
444
555
666
777
888
999
程序将返回
[[111, 222, 333], [444, 555, 666], [777, 888, 999]]
发生这种情况是因为input()位于最内层循环内,因此被调用了 9 次。
因此,如果您想输入所示的由空格分隔的值,您可以使用列表理解将其转换为数字列表:
row = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
for i in range(row): # A for loop for row entries
matrix_input.append([int(k) for k in input().split(' ')])
for out in matrix_input:
print('{0} {1} {2}'.format(*out))
这将要求三个条目,这些条目沿空格分割并转换为整数。如果你想要浮动,你可以使用float(k)而不是int(k)。print 命令使用解包并返回行for ... in。
或者,您可以使用' '.join(),它更灵活:
for out in matrix_input:
print(' '.join([str(el) for el in out]))
这实际上是构造矩阵的逆运算。
TA贡献1817条经验 获得超14个赞
def matrix():
row = int(3)
column = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
for i in range(row): # A for loop for row entries
ints =input()
entries = []
for a in ints:
entries.append(int(a))
matrix_input.append(entries)
for ele in matrix_input:
for d in ele:
print(d,end='')
print('')
matrix()
输入:
Enter the entries in a single line (separated by space):
130
304
603
输出:
130
304
603
TA贡献1818条经验 获得超8个赞
问题是您试图将整个字符串(每个 int 之间有空格的输入)转换为整数。
相反,您需要拆分输入。见下文:
def matrix():
row = int(3)
column = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
input_str = input()
entries = []
entries.extend([int(x) for x in input_str.split(' ')])
for item in entries:
print(item)
TA贡献1805条经验 获得超9个赞
这可以解决问题。
def matrix():
row = int(3)
column = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
for i in range(row): # A for loop for row entries
# ints = input().split()
while True:
ints = input().split()
if len(ints) == 3:
break
print("Invalid Input Received")
print("Enter the entries in a single line (separated by space): ")
entries = []
for a in ints:
entries.append(int(a))
matrix_input.append(entries)
print("Output")
for ele in matrix_input:
for d in ele:
print(d, end=' ')
print('')
添加回答
举报