2010-01-28 90 views
7

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

回答

14

元组是不可变的,因此是NamedTuples。他们不应该被改变!

this_prize._replace(choice = "Yay")使用关键字参数"choice"调用_replace。它不使用choice作为变量,并尝试用choice的名称替换字段。

this_prize._replace(**{choice : "Yay"})将使用任何choice是字段名

_replace返回一个新NamedTuple。你需要重新分配它:this_prize = this_prize._replace(**{choice : "Yay"})

只需使用一个字典或写一个普通的类!

+0

耶!这就是我需要知道的。谢谢 – 2010-01-28 20:38:45

+0

我试图优化数据结构的速度。 我一直希望能使用namedtuples,但我必须改变它们。也许我将不得不使用别的东西。见: http://stackoverflow.com/questions/2127680/python-optimizing-or-at-least-getting-fresh-ideas-for-a-tree-generator – 2010-01-28 21:14:39

+0

我有一个情况,我不会改变最的元组,但只有其中的几个,所以'_replace'是要走的路。这个答案帮了我很多(比官方文档更多)。 – JulienD 2016-01-02 17:51:57

2
>>> 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 
+0

感谢您的回复。我明白你的意思了。 – 2010-01-28 20:39:54

+1

但是真的,你为什么使用这个命名的元组?这听起来像你想要一个字典。 – jcdyer 2010-01-28 20:54:26

相关问题