Pythonは:フィールド名として変数とnamedtuple._replaceを使用します

StackOverflow https://stackoverflow.com/questions/2157561

  •  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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top