Python: 从 namedtuple 列表中获取参数值列表
Python: take a list of values of parameter from a list of namedtuple
我有一个 namedtuples
的列表,例如:
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]
我想在列表的元素中获取给定参数的所有值的列表,例如:param 'arg1
' 有一个 list [1,0,1,1,2]
和 param 'arg2
' 有一个 list [2,2,0,2,3]
如果我事先知道参数,我可以使用 for 循环来实现,因为
values = []
for e in full_list:
values.append(e.arg1)
但是我如何编写一个可以用于任何参数的通用函数?
如果您想通过 "position" 访问它,您可以使用 operator.attrgetter
if you want to get it by the attribute name or operator.itemgetter
:
>>> 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]
您可以使用 getattr
访问命名属性,给定属性为字符串:
def func(param, lst):
return [getattr(x, param) for x in lst]
print func('arg2', full_list)
# [2, 2, 0, 2, 3]
在python中有一个built-in function
that enables access to attributes via their name, it is call getattr
(there is also a similar setter function: setattr
).
它的签名是getattr(object, name)。
对于你的情况,我建议:
attribute_list = ['arg1', 'arg2', 'arg3']
Example = namedtuple('Example', attribute_list)
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]
values = []
for e in full_list:
for attr in attribute_list:
values.append(attr)
我有一个 namedtuples
的列表,例如:
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]
我想在列表的元素中获取给定参数的所有值的列表,例如:param 'arg1
' 有一个 list [1,0,1,1,2]
和 param 'arg2
' 有一个 list [2,2,0,2,3]
如果我事先知道参数,我可以使用 for 循环来实现,因为
values = []
for e in full_list:
values.append(e.arg1)
但是我如何编写一个可以用于任何参数的通用函数?
如果您想通过 "position" 访问它,您可以使用 operator.attrgetter
if you want to get it by the attribute name or operator.itemgetter
:
>>> 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]
您可以使用 getattr
访问命名属性,给定属性为字符串:
def func(param, lst):
return [getattr(x, param) for x in lst]
print func('arg2', full_list)
# [2, 2, 0, 2, 3]
在python中有一个built-in function
that enables access to attributes via their name, it is call getattr
(there is also a similar setter function: setattr
).
它的签名是getattr(object, name)。
对于你的情况,我建议:
attribute_list = ['arg1', 'arg2', 'arg3']
Example = namedtuple('Example', attribute_list)
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]
values = []
for e in full_list:
for attr in attribute_list:
values.append(attr)