【发布时间】:2016-08-02 02:30:11
【问题描述】:
我要做的是检查字典中的“inv”键中是否存在“dragonLoot”中的值。如果是,我想给那个值加 1,如果不是,我想用那个值创建一个新键并加 1。
我想我已经得到了 if,else 部分正确,但我有些努力让它循环并接收 TypeError: list indices must be integers, not str 错误。代码如下:
#Inventory and the Loot value
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#Function to loop through the items in the list
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for j, k in inventory.items():
print(str(k) + ' ' + j)
item_total += k
print('Total number of items: %s' % str(item_total))
#Where the problem occur
def addToInventory(inventory, addedItems):
for i in addedItems:
if addedItems[i] in inventory.keys():
#Edit: I see an error here now, but I will fix it after I get the loop working
inventory[addedItems[i]] + 1
else:
inventory.setdefault(addedItems[i], 1)
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
我尝试了很多其他在 StackOverflow 上找到的解决方案,但没有任何效果。是不是我造成的其他一些与循环本身无关的错误?
完整的追溯:
Traceback (most recent call last):
File "C:/Users/*****/Dropbox/*****", line 19, in <module>
inv = addToInventory(inv, dragonLoot)
File "C:/Users/*****/Dropbox/*****", line 14, in addToInventory
if addedItems[i] in inventory.keys():
TypeError: list indices must be integers, not str
【问题讨论】:
-
什么是完整的回溯?
-
Traceback(最近一次调用最后一次):文件“C:/Users/***/Dropbox/Programming/simpleGame.py”,第 19 行,在
inv = addToInventory(inv, dragonLoot ) 文件“C:/Users/***/Dropbox/Programming/simpleGame.py”,第 14 行,在 addToInventory if addedItems[i] in inventory.keys(): TypeError: list indices must be integers, not str跨度> -
仅供参考,您几乎不需要
.keys()- dict 上的in运算符已经检查了键列表。
标签: python list python-3.x dictionary