简体   繁体   English

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

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

Probably this question was already asked (if so, please help me, but I couldn't find).可能已经问过这个问题(如果是这样,请帮助我,但我找不到)。 So, my question is:所以,我的问题是:

How to check if a value exists in list's column如何检查列表列中是否存在值

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],
        ]

I want something like this:我想要这样的东西:

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

I know iterating through the list and checking column values one by one, but is there better solution?我知道遍历列表并一一检查列值,但是有更好的解决方案吗? Or what would be the best solution?或者什么是最好的解决方案?

You can directly check whether the desired element is in the sequence of "n'th elements of each row":您可以直接检查所需元素是否在“每行第n个元素”的序列中:

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

Note that lists are made to represent arbitrarily sized collections of arbitrary items – that's not ideal for regular data structures such as matrices or "list of columns".请注意,列表用于表示任意项目的任意大小的集合——这对于常规数据结构(如矩阵或“列列表”)来说并不理想。 You might want to use numpy or a similar library instead, since it has a concept for multi-dimensional arrays.您可能想改用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]

perhaps something like也许像

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