简体   繁体   English

索引和查找namedtuples列表中的值

[英]indexing and finding values in list of namedtuples

I have a namedtuple like the following, 我有一个如下的命名元组,

tup = myTuple  (
                a=...,
                b=...,
                c=...,
                )

where ... could be any value(string, number, date, time, etc). where ...可以是任何值(字符串,数字,日期,时间等)。 Now, i make a list of these namedtuples and want to find, lets say c=1 and the corresponding value of a and b. 现在,我列出了这些命名元组并想要查找,假设c = 1以及a和b的对应值。 Is there any pythonic way of doing this? 有没有pythonic方式这样做?

Use List Comprehension, like a filter, like this 使用列表理解,像这样的过滤器

[[record.a, record.b] for record in records if record.c == 1]

For example, 例如,

>>> myTuple = namedtuple("Test", ['a', 'b', 'c', 'd'])
>>> records = [myTuple(3, 2, 1, 4), myTuple(5, 6, 7, 8)]
>>> [[record.a, record.b] for record in records if record.c == 1]
[[3, 2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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