问题
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