的Python:使用namedtuple._replace具有可变的字段名
-
23-09-2019 - |
题
我可以参考使用的变量的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
解决方案
元组是不可变的,因此是NamedTuples。他们不应该被改变!
this_prize._replace(choice = "Yay")
呼叫_replace
与关键字参数"choice"
。它不使用choice
作为变量,并尝试通过choice
的名称来代替字段。
this_prize._replace(**{choice : "Yay"} )
将使用任何choice
是作为字段名
_replace
返回一个新NamedTuple。你需要reasign它:this_prize = this_prize._replace(**{choice : "Yay"} )
只需使用一个字典或写一个普通的类代替!
其他提示
>>> 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
不隶属于 StackOverflow