繁体   English   中英

检查列表列中是否存在值(Python)

[英]Check if value exists in list's column (Python)

可能已经问过这个问题(如果是这样,请帮助我,但我找不到)。 所以,我的问题是:

如何检查列表列中是否存在值

numbers = [
            [5, 3, 0, 0, 7, 0, 0, 0, 0],
            [6, 0, 0, 1, 9, 5, 0, 0, 0],
            [0, 9, 8, 0, 0, 0, 0, 6, 0],
            [8, 0, 0, 0, 6, 0, 0, 0, 3],
            [4, 0, 0, 8, 0, 3, 0, 0, 1],
            [7, 0, 0, 0, 2, 0, 0, 0, 6],
            [0, 6, 0, 0, 0, 0, 2, 8, 0],
            [0, 0, 0, 4, 1, 9, 0, 0, 5],
            [0, 0, 0, 0, 8, 0, 0, 7, 9],
        ]

我想要这样的东西:

if 4 in numbers.columns[2]: # checking if 4 exists in column 2
    print("dang")

我知道遍历列表并一一检查列值,但是有更好的解决方案吗? 或者什么是最好的解决方案?

您可以直接检查所需元素是否在“每行第n个元素”的序列中:

if 8 in (row[2] for row in numbers):
   print("found")

请注意,列表用于表示任意项目的任意大小的集合——这对于常规数据结构(如矩阵或“列列表”)来说并不理想。 您可能想改用numpy或类似的库,因为它具有多维数组的概念。

import numpy as np

#        v---------------v a regular array of row x column size
matrix = np.array(numbers)

#            v----------v of all (:) rows take the third (2) element
found = 8 in matrix[:, 2]

也许像

if any(4 == row[2] for row in numbers):
   print('dang')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM