我正在编写一个函数,它接受一个命名元组,并且必须返回该元组的超集。
例如,如果我要收到这样的命名元组:
Person(name='Bob', age=30, gender='male')
我想返回一个如下所示的元组:
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 个字段。
您可以尝试使用字典解包来缩短它,例如:
tuple = new_tuple(x=0, **other_tuple._asdict())
接受的版本已损坏,您将收到
new_tuple() got multiple values for argument 'x'
错误。
您应该使用
_replace
来代替:
https://docs.python.org/3/library/collections.html#collections.somenamedtuple._replace