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