检查列表中是否存在值为x的命名元组。

4

我想知道一个namedtuple是否存在于列表中,类似于:

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

有没有一种Pythonic(或非Pythonic)的方式来做这个?类似这样的东西:
 namedtuples = [namedtuple_1, namedtuple_2, namedtuple3]
 if (namedtuple with value x = 1) in namedtuples:
      do stuff()
1个回答

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

运行得非常好,谢谢。 - user1500452

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接