Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
Abhishek Thakur Avatar asked Apr 16 '14 17:04

Abhishek Thakur


1 Answers

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]]
like image 187
thefourtheye Avatar answered Sep 19 '22 13:09

thefourtheye