Python:从namedtuple列表中获取参数值列表

标签 python list 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]

我想在列表的元素中列出给定参数的所有值,例如:对于参数 'arg1' 有一个 list [1, 0,1,1,2] 并且参数 'arg2' 有一个 list [2,2,0,2,3]

如果我事先知道参数,我可以使用 for 循环来实现它,如

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

但是我怎样才能编写一个可以用于任何参数的通用函数呢?

最佳答案

你可以使用 operator.attrgetter如果你想通过属性名或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]

关于Python:从namedtuple列表中获取参数值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45168700/

相关文章:

python - 使用字符串的值调用值的列表

python - Wagtail:更改 Page.title 的 max_length

python - 导入模块(但不使用它)会降低 Python 的性能吗?

python - Tkinter TTK 按钮粗体字体

python - 如何验证 namedtuple 值?

python - 创建namedtuple时避免输入两次名称

python - 优化: Search the best way to compare two list of dict (Python)

java - 在 Scala 中从 java.util.Set 构造一个 java.util.List

list - F#:如何打印完整列表(Console.WriteLine() 仅打印前三个元素)

python - 可选关键字参数的命名元组和默认值