簡體   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