在Python中合并命名元组的简单方法是什么?

2024-10-03 06:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想合并两个namedtuples而不丢失键名。如果,我只是用“+”运算符进行合并,结果得到一个元组,但没有名称。

例如:

n [1]: from collections import namedtuple

In [2]: A = namedtuple("A", "a b c")

In [4]: B = namedtuple("B", "d e")

In [5]: a = A(10, 20, 30)

In [6]: b = B(40, 50)

In [7]: a + b
Out[7]: (10, 20, 30, 40, 50)

正如您在上面的例子中看到的,a+b的结果没有与它们相关联的名称。

但是,我可以通过创建第三个namedtuple来实现它,它有来自a和B的字段

In [8]: C = namedtuple("C", A._fields + B._fields)

In [9]: C(*(a + b))
Out[9]: C(a=10, b=20, c=30, d=40, e=50)

这是正确的方法还是有更好的方法?


Tags: 方法infromimport名称fields运算符out
3条回答

Python不会自动创建新的类namedtuple。您必须自己定义组合的namedtuple

A = namedtuple("A", "a b c")
B = namedtuple("B", "d e")
AB = namedtuple("AB", "a b c d e")

a = A(1,2,3)
b = B(4,5)
ab = AB(*(a+b))

>>> a
A(a=1, b=2, c=3)
>>> b
B(d=4, e=5)
>>> ab
AB(a=1, b=2, c=3, d=4, e=5)

就普通的Python而言,您已经非常清楚了,但是如果您使用的是Python 3.5+,则可以进行额外的简化。

>>> from collections import namedtuple
>>> A = namedtuple("A", "a b c")
>>> B = namedtuple("B", "d e")
>>> a = A(10, 20, 30)
>>> b = B(40, 50)
>>> C = namedtuple("C", A._fields + B._fields)
>>> C(*(a + b))
C(a=10, b=20, c=30, d=40, e=50)
>>> #Available in Python 3.5+
>>> C(*a, *b)
C(a=10, b=20, c=30, d=40, e=50)

此外,如果您发现自己经常这样做,可以使用以下函数来消除样板代码:

>>> from functools import reduce
>>> from itertools import chain
>>> from operator import add
>>> def namedtuplemerge(*args):
...     cls = namedtuple('_'.join(arg.__class__.__name__ for arg in args), reduce(add, (arg._fields for arg in args)))
...     return cls(*chain(*args))
...
>>> namedtuplemerge(a, b)
A_B(a=10, b=20, c=30, d=40, e=50)

一些观察:

  • 一般来说,当您试图合并两个恰好具有相同名称字段的namedtuples时,Python不知道该怎么办。也许这就是为什么没有运算符或函数。

  • documentation of ^{}说:

Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

这表明您的方法很好,甚至可能是由namedtuple代码的作者暗示的。

相关问题 更多 >