简体   繁体   中英

Check if namedtuple with value x exists in list

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()

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM