擅长:python、mysql、java
<p>首先需要将set更改为tuple,因为它在遍历列表时跳过重复的条目。你知道吗</p>
<p>以下是工作代码:</p>
<pre><code>stuff = {'rope': 1, 'torch': 6, 'gold coin': 40, 'dagger': 1, 'arrow': 12}
dragonLoot = ('gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby')
def addToInventory(inventory, addedItems):
#Iterate through the list
for k in addedItems:
#if key not in the dictionary, add to the dictionary and set its value to zero
inventory.setdefault(k,0)
#increment value by one
inventory[k] = inventory[k] + 1
print(str(inventory[k]))
def displayInventory(inventory):
print('Inventory:')
itemTotal = 0
#iterate through the dictionary and print the key/values
for k, v in inventory.items():
print(k + ': ' + str(v))
itemTotal = itemTotal + v
print ('Total number of items: ' + str(itemTotal))
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
</code></pre>