7

我可以使用变量引用命名元组字段吗?

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
4

2 回答 2

15

元组是不可变的,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 或编写普通类!

于 2010-01-28T20:32:48.413 回答
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
于 2010-01-28T20:18:23.047 回答