Python:复制具有相同属性/字段的命名元组

Python: Copying named tuples with same attributes / fields

我正在编写一个接受命名元组的函数,并且必须 return 该元组的超集。

例如,如果我要接收这样的命名元组:

Person(name='Bob', age=30, gender='male')

我想要 return 一个看起来像这样的元组:

Person(name='Bob', age=30, gender='male', x=0)

目前我正在这样做:

tuple_fields = other_tuple[0]._fields
tuple_fields = tuple_fields + ('x')
new_tuple = namedtuple('new_tuple', tuple_fields)

很好,但我不想像这样复制每个字段:

tuple = new_tuple(name=other_tuple.name, 
                  age=other_tuple.age, 
                  gender=other_tuple.gender, 
                  x=0)

我希望能够遍历第一个对象中的每个对象并将它们复制过来。我的实际元组是 30 个字段。

您可以尝试利用 dict 解包来缩短它,例如:

tuple = new_tuple(x=0, **other_tuple._asdict())