Make sure matrix row took from text file are same

2019-09-22 13:33发布

问题:

This question is an exact duplicate of:

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

so I have this code to input a matrix from a text file:

            import os
            path = input('enter file path')
            there = os.path.exists(path)
            if there == False:
                print('Invalid path')
                menu()
            matrix = open(path).read()
            matrix = [item.split() for item in matrix.split('\n')]
            menu_matrix(matrix)
        except(ValueError,TypeError):
            print('Invalid character in text file')

My question is how to prevent to let pass a matrix that has different row length?For example a text file containing:

1 2 3
4 3 2 2
1 2 4 7 7

Should print something like 'row doesnt have the same length in the text file' and not let it pass.Im not quite sure of how to do that.

Thanks

回答1:

Just loop through the array, calling len(array[index]) on each sub array, and then checking if it is equal to the length of the first line.