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!"
发布于 2014-10-19 01:10:13
您的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!"https://stackoverflow.com/questions/26446232
复制相似问题