Make sure matrix row took from text file are same length(python3) [duplicate]

时间秒杀一切 提交于 2019-12-13 09:05:10

问题


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.



来源:https://stackoverflow.com/questions/23532548/make-sure-matrix-row-took-from-text-file-are-same-lengthpython3

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