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

后端 未结 2 1114
执念已碎
执念已碎 2021-01-26 12:44

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 != []:
               


        
2条回答
  •  失恋的感觉
    2021-01-26 13:38

    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$ 
    

提交回复
热议问题