使用 nametuple._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
Can I reference a namedtuple fieldame using a 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
元组是不可变的,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"} )
只需使用字典或编写普通类即可!
Tuples are immutable, and so are NamedTuples. They are not supposed to be changed!
this_prize._replace(choice = "Yay")
calls_replace
with the keyword argument"choice"
. It doesn't usechoice
as a variable and tries to replace a field by the name ofchoice
.this_prize._replace(**{choice : "Yay"} )
would use whateverchoice
is as the fieldname_replace
returns a new NamedTuple. You need to reasign it:this_prize = this_prize._replace(**{choice : "Yay"} )
Simply use a dict or write a normal class instead!