Frage

Kann ich verweisen auf ein namedtuple fieldame eine 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
War es hilfreich?

Lösung

Tupeln sind unveränderlich, und so sind NamedTuples. Sie sollen nicht geändert werden!

this_prize._replace(choice = "Yay") Anrufe _replace mit dem Stichwort Argument "choice". Dabei spielt es keine choice als Variable und versucht verwenden, um ein Feld mit dem Namen choice zu ersetzen.

this_prize._replace(**{choice : "Yay"} ) würde verwenden, was choice als Feldname ist

_replace gibt einen neuen NamedTuple. Sie müssen es reasign: this_prize = this_prize._replace(**{choice : "Yay"} )

Sie einfach einen dict verwenden oder eine normale Klasse schreiben statt!

Andere Tipps

>>> 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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top