确保从文本文件中提取的矩阵行的长度相同(python3) [英] Make sure matrix row took from text file are same length(python3)

查看:80
本文介绍了确保从文本文件中提取的矩阵行的长度相同(python3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码可以从文本文件中输入矩阵:

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.

谢谢

推荐答案

只需遍历数组,在每个子数组上调用len(array[index]),然后检查它是否等于第一行的长度.

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.

这篇关于确保从文本文件中提取的矩阵行的长度相同(python3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆