检查列表中是否存在值为x的namedtuple

时间:2013-12-05 23:36:43

标签: python list namedtuple

我想查看列表中是否存在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()

1 个答案:

答案 0 :(得分:5)

使用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]