检查列表中是否存在值为x的namedtuple(Check if namedtuple with value x exists in list)

编程入门 行业动态 更新时间:2024-10-14 10:44:04
检查列表中是否存在值为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()

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

最满意答案

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

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]

更多推荐

本文发布于:2023-08-03 23:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405317.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:值为   是否存在   列表中   namedtuple   exists

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!