inventory = {
'gold' : 500,
'sack' : ['rock', 'copper wire'],
'weapons rack' : ['pistol', 'MP-5', 'grenade'],
'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'],
}
print "You have " + inventory['gold'][0] + " coins!"
我收到错误消息:
line 8, in <module>
print "You have " + inventory['gold'] + " coins!"
TypeError: 'int' object has no attribute '__getitem__'
为什么控制台不打印"You have 500 gold coins!"
答案 0 :(得分:2)
您的gold
条目不是列表;您正在尝试索引500
整数。删除[0]
:
print "You have", inventory['gold'], "coins!"
请注意,我使用的是逗号,而不是+
,因为您不能只连接字符串和整数。另一种方法是首先将整数转换为字符串:
print "You have " + str(inventory['gold']) + " coins!"
您还可以将黄金值放入列表中:
inventory = {
'gold' : [500],
'sack' : ['rock', 'copper wire'],
'weapons rack' : ['pistol', 'MP-5', 'grenade'],
'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'],
}
请注意[...]
值周围的500
方括号。然后,您的[0]
再次适用:
print "You have", inventory['gold'][0], "coins!"