我可以使用变量引用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
Run Code Online (Sandbox Code Playgroud)
Joc*_*zel 14
元组是不可变的,NamedTuples也是如此.它们不应该被改变!
this_prize._replace(choice = "Yay")调用_replace与关键字参数"choice".它不用choice作变量并尝试用名称替换字段choice.
this_prize._replace(**{choice : "Yay"} )将使用任何choice作为字段名称
_replace返回一个新的NamedTuple.你需要重新签名:this_prize = this_prize._replace(**{choice : "Yay"} )
只需使用字典或写一个普通的课程!