简体   繁体   中英

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). Now, i make a list of these namedtuples and want to find, lets say c=1 and the corresponding value of a and b. Is there any pythonic way of doing this?

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

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