确保从文本文件中提取的矩阵行长度相同(python3)
因此,我有以下代码从文本文件中输入矩阵:确保从文本文件中提取的矩阵行长度相同(python3),python,matrix,row,text-files,Python,Matrix,Row,Text Files,因此,我有以下代码从文本文件中输入矩阵: import os path = input('enter file path') there = os.path.exists(path) if there == False: print('Invalid path') menu() matrix = open(path
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')
我的问题是如何防止传递具有不同行长度的矩阵?例如,包含以下内容的文本文件:
1 2 3
4 3 2 2
1 2 4 7 7
应该打印像“行在文本文件中的长度不相同”这样的内容,并且不要让它通过。我不太确定该怎么做
谢谢只需在数组中循环,在每个子数组上调用
len(array[index])
,然后检查它是否等于第一行的长度 你什么意思?谢谢你12分钟前就接受了答案。在12分钟的工作后,你不能只问同一个问题的细微变化。前面答案中的相同技巧在这里同样有效;将行长度相互比较,如果发现不匹配,则拒绝该数组。