7

変数を使用して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
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 に答える