Making sure length of matrix row is all the same (python3)

喜你入骨 提交于 2019-12-02 18:41:20

问题


so I have this python 3 code to input a matrix:

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)

However,if I enter

1 2 3
4 5 6 7
8 9 0 1 2

my code will let it pass,but you can notice that row 2 and 3 are not same length as row 1; how to prevent that? the row have to be same length as row 1,else it has to return an error message like 'line don't have the same length. I'm not quite sure of how to do that. Maybe:

for row in matrix:
    if len(row) == matrix[1]
        pass
    else:
       print('not same length')

But it doesn't work.

Thanks


回答1:


If you want match the first row length, Try this way,

Use len(matrix[0])

for row in matrix:
    if len(row) == len(matrix[0]):
        pass
    else:
       print('not same lenght')



回答2:


Use the builtin len() function and a break statement.

matrix = []
lop =True
while lop:
    line = input('Enter your line: ')
    if not line:
        lop=False
    if matrix != []:
        if len(line.split()) != len(matrix[-1]):
            print("Not same length")
            break
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row)

This runs as:

bash-3.2$ python3 matrix.py
Enter your line: 1 2 3
Enter your line: 4 5 6
Enter your line: 7 8 9 0
Not same length
bash-3.2$ 


来源:https://stackoverflow.com/questions/23532218/making-sure-length-of-matrix-row-is-all-the-same-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!