Python:使用 namedtuple._replace 和一个变量作为字段名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2157561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:55:46  来源:igfitidea点击:

Python: Using namedtuple._replace with a variable as a fieldname

pythonnamedtuple

提问by Peter Stewart

Can I reference a namedtuple fieldame using a variable?

我可以使用变量引用namedtuple fieldame 吗?

from collections import namedtuple
import random 

Prize = namedtuple("Prize", ["left", "right"]) 

this_prize = Prize("FirstPrize", "SecondPrize")

if random.random() > .5:
    choice = "left"
else:
    choice = "right"

#retrieve the value of "left" or "right" depending on the choice

print "You won", getattr(this_prize,choice)

#replace the value of "left" or "right" depending on the choice

this_prize._replace(choice  = "Yay") #this doesn't work

print this_prize

回答by Jochen Ritzel

Tuples are immutable, and so are NamedTuples. They are not supposed to be changed!

元组是不可变的,NamedTuples 也是如此。他们不应该被改变!

this_prize._replace(choice = "Yay")calls _replacewith the keyword argument "choice". It doesn't use choiceas a variable and tries to replace a field by the name of choice.

this_prize._replace(choice = "Yay")调用_replace与关键字参数"choice"。它不用choice作变量,而是尝试用 的名称替换字段choice

this_prize._replace(**{choice : "Yay"} )would use whatever choiceis as the fieldname

this_prize._replace(**{choice : "Yay"} )将使用任何choice作为字段名

_replacereturns a new NamedTuple. You need to reasign it: this_prize = this_prize._replace(**{choice : "Yay"} )

_replace返回一个新的 NamedTuple。您需要重新分配它:this_prize = this_prize._replace(**{choice : "Yay"} )

Simply use a dict or write a normal class instead!

只需使用字典或编写普通类即可!

回答by SilentGhost

>>> choice = 'left'
>>> this_prize._replace(**{choice: 'Yay'})         # you need to assign this to this_prize if you want
Prize(left='Yay', right='SecondPrize')
>>> this_prize
Prize(left='FirstPrize', right='SecondPrize')         # doesn't modify this_prize in place