我想合并两个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)
这是正确的方法还是有更好的方法?
Python不会自动创建新的类
namedtuple
。您必须自己定义组合的namedtuple
:就普通的Python而言,您已经非常清楚了,但是如果您使用的是Python 3.5+,则可以进行额外的简化。
此外,如果您发现自己经常这样做,可以使用以下函数来消除样板代码:
一些观察:
一般来说,当您试图合并两个恰好具有相同名称字段的namedtuples时,Python不知道该怎么办。也许这就是为什么没有运算符或函数。
documentation of ^{} 说:
这表明您的方法很好,甚至可能是由namedtuple代码的作者暗示的。
相关问题 更多 >
编程相关推荐