Python:使用带有变量的namedtuple._replace作为fieldname

时间:2010-01-28 20:02:00

标签: python namedtuple

我可以使用变量?

引用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

2 个答案:

答案 0 :(得分: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"} )

只需使用dict或写一个普通的类!

答案 1 :(得分:2)

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