可能已經問過這個問題(如果是這樣,請幫助我,但我找不到)。所以,我的問題是:
如何檢查串列列中是否存在值
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")
我知道遍歷串列并一一檢查列值,但是有更好的解決方案嗎?或者什么是最好的解決方案?
uj5u.com熱心網友回復:
您可以直接檢查所需元素是否在“每行第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]
uj5u.com熱心網友回復:
也許像
if any(4 == row[2] for row in numbers):
print('dang')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339433.html
上一篇:比較地圖和串列中的專案
