如何仅查看列表中所有列表中的第3个值

chi*_*ong 5 python

我有一个列表列表,我希望能够引用列表列表中的第1,第2,第3等列.这是我的列表代码:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
Run Code Online (Sandbox Code Playgroud)

我想能够说出类似的话:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
if (The fourth column in this matrix does not have any 1's in it):
    (then do something)
Run Code Online (Sandbox Code Playgroud)

我想知道括号中的东西是什么python语法.

Ósc*_*pez 2

尝试这个:

if all(row[3] != 1 for row in matrix):
    # do something
Run Code Online (Sandbox Code Playgroud)

row[3]部分查看一行的第四个元素,该for row in matrix部分查看矩阵中的所有行 - 这会生成一个列表,其中包含所有行中的所有第四个元素,即整个第四列。现在,如果第四列中的所有元素都与一个不同,则满足条件,您可以在if.

更传统的方法是:

found_one = False
for i in xrange(len(matrix)):
    if matrix[i][3] == 1:
        found_one = True
        break
if found_one:
    # do something
Run Code Online (Sandbox Code Playgroud)

在这里,我迭代i第四列(索引)的所有行(索引3),并检查元素是否等于 1: if matrix[i][3] == 1:。请注意,for循环从0索引到矩阵的“高度”减一,这就是该xrange(len(matrix))部分所说的。