Python: El uso de namedtuple._replace con una variable como un nombre de campo
-
23-09-2019 - |
Pregunta
¿Puedo hacer referencia a un fieldame namedtuple usando una variable?
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
Solución
Las tuplas son inmutables, y también lo son NamedTuples. No se supone que ser cambiado!
llamadas this_prize._replace(choice = "Yay")
_replace
con el "choice"
argumento de palabra clave. No utiliza choice
como una variable y trata de sustituir un campo con el nombre de choice
.
this_prize._replace(**{choice : "Yay"} )
podría usar cualquier choice
es como el nombre del campo
_replace
devuelve una nueva NamedTuple. Es necesario que se reasign: this_prize = this_prize._replace(**{choice : "Yay"} )
Simplemente usar un diccionario o escribir una clase normal en vez!
Otros consejos
>>> 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow