简体   繁体   English

如何._replace() python3 namedtuple object 的多个元素的值?

[英]How to ._replace() the value of multiple elements of a python3 namedtuple object?

Below is how I create and use a namedtuple object:下面是我如何创建和使用命名元组 object:

>>> from collections import namedtuple
>>> labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> data = namedtuple('data', labels)
>>> my_data1 = data(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7, i=8, j=9)
>>> my_data1
data(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7, i=8, j=9)

Instead of having to manually type this multiple times:不必多次手动输入:

my_data1 = data(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7, i=8, j=9)

How do I write a for-loop or use a comprehension approach to write this?我如何编写一个 for 循环或使用理解方法来编写它? Eg if values is a list object, eg list(range(10)) or a list of any values, how do I create a new instance of data with a for-loop and different list of values?例如,如果 values 是一个列表 object,例如 list(range(10)) 或任何值的列表,我如何使用 for 循环和不同的值列表创建一个新的data实例?

You can zip() the labels and values into a tuple list, then dict() it and pass to your data() constructor as keyword arguments:您可以将标签和值zip()到元组列表中,然后dict()并将其作为关键字 arguments 传递给您的data()构造函数:

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
kwargs = dict(zip(labels, values)))
my_data1 = data(**kwargs))

If you want a one-liner you can do something like this:如果你想要一个单行,你可以这样做:

from inspect import signature
my_data1 = data(**{i: j for i, j in zip(signature(data).parameters, range(10))})

This basically gets the parameters of the namedtuple and gets the numbers 0-9 and zips them together.这基本上是获取namedtuple的参数并获取数字0-9并将它们压缩在一起。 With some dictionary comprehension magic I created a dictionary with the keys being the parameters of the named tuple and the values being the actual values (the numbers).通过一些字典理解魔法,我创建了一个字典,键是命名元组的参数,值是实际值(数字)。 At the end I unpacked the dictionary and put everything inside of the data namedtuple.最后,我解压缩了字典并将所有内容放入数据命名元组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM