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

时间:2011-12-27 15:27:31

标签: 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],
    ]

我希望能够说出类似的内容:

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)

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

3 个答案:

答案 0 :(得分:4)

执行所要求的标准方法是执行列表理解

  

if(此矩阵中的第四列中没有任何1):

翻译成:

>>>if not any([1 == row[3] for row in matrix])

但是,根据您需要执行此操作的频率,矩阵的大小等等,您可能希望查看numpy,因为更容易(并且非常快)地处理列。一个例子:

>>> import numpy as np
>>> matrix = np.random.randint(0, 10, (5, 5))
>>> matrix
array([[3, 0, 9, 9, 3],
       [5, 7, 7, 7, 6],
       [5, 4, 6, 2, 2],
       [1, 3, 5, 0, 5],
       [3, 9, 7, 8, 6]])
>>> matrix[..., 3]  #fourth column
array([9, 7, 2, 0, 8])

答案 1 :(得分:2)

试试这个:

if all(row[3] != 1 for row in matrix):
    # do something

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

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

答案 2 :(得分:0)

if 1 in [row[3] for row in matrix]: