Python: Copying named tuples with same attributes / fields

为君一笑 提交于 2019-12-10 17:22:58

问题


I am writing a function that takes a named tuple and must return a super set of that tuple.

For example if I was to receive a named tuple like this:

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

I want to return a tuple that looks like this:

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

Currently I am doing this:

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

Which is fine, but I do not want to have to copy each field like this:

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

I would like to be able to just iterate through each object in the FIRST object and copy those over. My actual tuple is 30 fields.


回答1:


You could try utilizing dict unpacking to make it shorter, eg:

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


来源:https://stackoverflow.com/questions/40980775/python-copying-named-tuples-with-same-attributes-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!