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?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With