Indexing and finding values ​​in a namedtuples list

I have namedtuple as below

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

where ... can be any value (string, number, date, time, etc.). Now, I am making a list of these namedtuples and want to find, say c = 1 and the corresponding value of a and b. Is there any pythonic way to do this?

+4
source share
1 answer

Use a list like a filter like this

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

For instance,

>>> 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]]
+5
source

Source: https://habr.com/ru/post/1536836/


All Articles