Make sure matrix row took from text file are same

2019-09-22 13:43发布

This question is an exact duplicate of:

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条回答
看我几分像从前
2楼-- · 2019-09-22 14:24

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.

查看更多
登录 后发表回答