Check if namedtuple with value x exists in list

三世轮回 提交于 2019-12-10 22:54:41

问题


I want to see if a namedtuple exists in a list, similar to:

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

is there a pythonic (or not) way to do this? Something like:

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

回答1:


Use any:

Demo:

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


来源:https://stackoverflow.com/questions/20413080/check-if-namedtuple-with-value-x-exists-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!