Pergunta

Posso referenciar um nome de campo nomeadotuple usando uma variável?

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
Foi útil?

Solução

Tuplas são imutáveis, assim como NamedTuples.Eles não deveriam ser alterados!

this_prize._replace(choice = "Yay") chamadas _replace com o argumento da palavra-chave "choice".Não usa choice como uma variável e tenta substituir um campo pelo nome de choice.

this_prize._replace(**{choice : "Yay"} ) usaria qualquer coisa choice é como o nome do campo

_replace retorna um novo NamedTuple.Você precisa reatribuí-lo: this_prize = this_prize._replace(**{choice : "Yay"} )

Basta usar um dict ou escrever uma classe normal!

Outras dicas

>>> 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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top