我可以使用變量引用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