【发布时间】:2022-01-21 14:12:26
【问题描述】:
我正在编写游戏库存代码,但我的添加到库存功能中有一条错误消息。 我在这里要做的是创建一个新键,如果该项目尚未在字典中并将其赋值为 1,如果该项目已经在库存中,则将其值增加 1。 很高兴我得到任何帮助:D
def add_to_inventory(inventory, added_items):
for row in inventory:
if added_items[row] not in inventory:
inventory[added_items[row]] = 1
if added_items[row] in inventory:
inventory[added_items[row]] +=1
这是我得到的错误:
TypeError: tuple indices must be integers or slices, not str
【问题讨论】:
-
我想你想在
added_items上运行for循环而不是inventory... -
请显示complete 错误信息,并尝试阅读和理解错误信息。你认为
TypeError是什么意思?你认为它抱怨的是什么tuple,你认为它抱怨的是什么index?该索引值的类型是什么?索引must be an integer or a slice和str不起作用对您来说有意义吗?接下来看数据。tuple- 应该是tuple?它的索引呢? -
另见ericlippert.com/2014/03/05/how-to-debug-small-programs。错误消息并不是让专家知道如何解决问题的神奇词汇。它们是对问题的解释——任何人都可以学会理解,但只有在上下文中考虑它们并通过跟踪程序的逻辑。你有你的整个程序。我们有六行。
-
(不是的意思是“向我们展示你的整个程序”。它的意思是“向后追溯并尝试找出值的来源,尤其是检查是否有什么东西不是你期望的那样”。)
标签: python dictionary