簡體   English   中英

檢查列表中是否存在值為x的namedtuple

[英]Check if namedtuple with value x exists in list

我想看看列表中是否存在一個namedtuple,類似於:

numbers = [1, 2, 3, 4, 5]
if 1 in numbers:
      do_stuff()

是否有pythonic(或非)方式這樣做? 就像是:

 namedtuples = [namedtuple_1, namedtuple_2, namedtuple3]
 if (namedtuple with value x = 1) in namedtuples:
      do stuff()

使用any

演示:

>>> from collections import namedtuple
>>> A = namedtuple('A', 'x y')
>>> lis = [A(100, 200), A(10, 20), A(1, 2)]
>>> any(a.x==1 for a in lis)
True
>>> [getattr(a, 'x')==1 for a in lis]
[False, False, True]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM