确保矩阵行的长度都相同(python3) [英] Making sure length of matrix row is all the same (python3)

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

问题描述

所以我有以下python 3代码来输入矩阵:

so I have this python 3 code to input a matrix:

matrix = []
lop=True
while lop:
    line = input()
    if not line:
        lop=False
    if matrix != []:
        if len(line.split()) != len(matrix[-1]):
            print("Not same length")
            menu()
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row)

但是,如果我输入

1 2 3
4 5 6 7
8 9 0 1 2

我的代码会让它通过,但是您会注意到第2行和第3行的长度与第1行的长度不同;怎么预防呢?该行的长度必须与第1行的长度相同,否则必须返回一条错误消息,例如'line not have the same length.我不太确定该怎么做.也许:

my code will let it pass,but you can notice that row 2 and 3 are not same length as row 1; how to prevent that? the row have to be same length as row 1,else it has to return an error message like 'line don't have the same length. I'm not quite sure of how to do that. Maybe:

for row in matrix:
    if len(row) == matrix[1]
        pass
    else:
       print('not same length')

但这是行不通的.

谢谢

推荐答案

如果要匹配第一行长度,请尝试这种方式,

If you want match the first row length, Try this way,

使用len(matrix[0])

for row in matrix:
    if len(row) == len(matrix[0]):
        pass
    else:
       print('not same lenght')

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

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