Python 使用namedtuple.\u替换为变量作为字段名

Python 使用namedtuple.\u替换为变量作为字段名,python,namedtuple,Python,Namedtuple,我可以使用变量引用namedtuple字段名吗 from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5:

我可以使用变量引用namedtuple字段名吗

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

元组是不可变的,命名的元组也是不可变的。他们不应该被改变

此\u奖。\u replace(choice=“Yay”)
调用
\u用关键字参数
“choice”
替换
。它不使用
choice
作为变量,并尝试用
choice
的名称替换字段

这个奖。\u replace(**{choice:“Yay”})
将使用
choice
中的任何内容作为字段名

\u replace
返回一个新的命名元组。您需要重新设计它:
this\u prize=this\u prize.\u replace(**{choice:“Yay”})


只需使用dict或编写普通类即可

谢谢你的回复。我明白你的意思。但真的,你为什么要用一个命名的元组呢?听起来你想要一个dict。我正在尝试优化数据结构以提高速度。我希望我可以使用namedtuples,但我必须在适当的地方更改它们。也许我得用点别的。请看:我曾经遇到过这样一种情况:我不会修改大多数元组,但只修改其中的少数元组,因此
\u replace
是一种方法。这个答案对我帮助很大(比官方文件还大)。
>>> 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