Python函数all的行为不符合预期

2024-05-03 08:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python中的all函数来搜索矩阵,但它的行为并不像预期的那样。我假设matrix会输出True,而matrix2会输出False。我错过了什么

  matrix= [[1,1,1,1,1,1,1,1],
           [1,1,1,1,1,1,1,1],
           [1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1],
                [1,1,1,1,1,1,1,1],
                [1,1,1,1,1,1,1,1]]

matrix2= [[0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0]]


def isComplete(m):
    return all(item != 0 for item in m)

print isComplete(matrix)
print isComplete(matrix2)

输出:

True
True

Tags: 函数infalsetrueforreturndef矩阵
3条回答

只需更改isComplete()

def isComplete(m):
    return all(j != 0 for item in m for j in item)

在代码只检查list(non empty list)之前,这就是它返回True的原因

这里必须使用嵌套循环,因为矩阵包含列表而不是实际的数字

return all(item != 0 for line in m for item in line)

您需要迭代嵌套列表,因此需要嵌套理解

return all(item != 0 for sublist in m for item in sublist)

相关问题 更多 >