Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: take a list of values of parameter from a list of namedtuple

I have a list of namedtuples, as an example below:

from collections import namedtuple
Example = namedtuple('Example', ['arg1', 'arg2', 'arg3'])
e1 = Example(1,2,3)
e2 = Example(0,2,3)
e3 = Example(1,0,0)
e4 = Example(1,2,3)
e5 = Example(2,3,5)
full_list = [e1, e2, e3, e4, e5]

I would like to take a list of all values of a given parameter among the elements in the list, thus for example: for param 'arg1' to have a list [1,0,1,1,2] and for param 'arg2' to have a list [2,2,0,2,3]

If I know the parameter in advance I can make it using a for loop, as

values = []
for e in full_list:
    values.append(e.arg1)

But how can I write a universal function which I can use for any parameter?

like image 300
Ziva Avatar asked Dec 12 '25 05:12

Ziva


2 Answers

You could use operator.attrgetter if you want to get it by the attribute name or operator.itemgetter if you want to access it by "position":

>>> import operator

>>> list(map(operator.attrgetter('arg1'), full_list))
[1, 0, 1, 1, 2]

>>> list(map(operator.itemgetter(1), full_list))
[2, 2, 0, 2, 3]
like image 109
MSeifert Avatar answered Dec 14 '25 18:12

MSeifert


You can use getattr to access the named attribute given the attribute as a string:

def func(param, lst):
   return [getattr(x, param) for x in lst]

print func('arg2', full_list)
# [2, 2, 0, 2, 3]
like image 22
Moses Koledoye Avatar answered Dec 14 '25 17:12

Moses Koledoye