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

2023-12-26

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

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

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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐