Python: Usando namedtuple._replace con una variabile come un nome di campo
-
23-09-2019 - |
Domanda
Posso fare riferimento a una fieldame namedtuple utilizzando una variabile?
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
Soluzione
Le tuple sono immutabili, e così sono NamedTuples. Essi non dovrebbero essere cambiate!
chiamate this_prize._replace(choice = "Yay")
_replace
con la "choice"
argomento chiave. Non usa choice
come variabile e cerca di sostituire un campo con il nome di choice
.
this_prize._replace(**{choice : "Yay"} )
avrebbe usato qualsiasi choice
è come il fieldname
_replace
restituisce una nuova namedtuple. È necessario reasign esso: this_prize = this_prize._replace(**{choice : "Yay"} )
Basta usare un dict o scrivere una classe normale, invece!
Altri suggerimenti
>>> 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow