我可以使用变量引用namedtuple fieldame吗?Python:使用namedtuple._replace和变量作为字段名称
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
耶!这就是我需要知道的。谢谢 – 2010-01-28 20:38:45
我试图优化数据结构的速度。 我一直希望能使用namedtuples,但我必须改变它们。也许我将不得不使用别的东西。见: http://stackoverflow.com/questions/2127680/python-optimizing-or-at-least-getting-fresh-ideas-for-a-tree-generator – 2010-01-28 21:14:39
我有一个情况,我不会改变最的元组,但只有其中的几个,所以'_replace'是要走的路。这个答案帮了我很多(比官方文档更多)。 – JulienD 2016-01-02 17:51:57