所以我有这个 python 3 代码来输入矩阵:
matrix = []
lop=True
while lop:
line = input()
if not line:
lop=False
if matrix != []:
if len(line.split()) != len(matrix[-1]):
print("Not same length")
menu()
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
但是,如果我输入
1 2 3
4 5 6 7
8 9 0 1 2
我的代码会让它通过,但你可以注意到第 2 行和第 3 行的长度与第 1 行的长度不同;如何防止呢?该行的长度必须与第 1 行相同,否则它必须返回一条错误消息,例如“行长度不同”。我不太确定该怎么做。或许:
for row in matrix:
if len(row) == matrix[1]
pass
else:
print('not same length')
但这不起作用。
Thanks
如果你想匹配第一行的长度,试试这个方法,
Use len(matrix[0])
for row in matrix:
if len(row) == len(matrix[0]):
pass
else:
print('not same lenght')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)