简体   繁体   中英

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":

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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