想象一下,被征服的龙的战利品被表示为这样的字符串:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
编写一个名为的函数addToInventory(inventory, addedItems),其中inventory参数是表示玩家的库存的字典(如上一个项目中所示),addedItems参数是一个列表dragonLoot。该addToInventory()函数应该返回一个表示更新的库存的字典。请注意,该addedItems列表可以包含相同项目的倍数。你的代码看起来像这样:
# inventory.py
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
item_total=item_total+v
print(k+' :',v)
print("Total number of items: " + str(item_total))
#stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
#displayInventory(stuff)
'''
输出如下:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62
'''
#! /usr/bin/env python3
def displayInventory(inventory):
print('Inventory:')
items_total = 0
for k,v in inventory.items():
print(str(v)+' ' + k)
items_total += v
print('Total number of items:'+str(items_total))
def addToInventory(inventory,addedItems):
for i in addedItems:
if i in inventory.keys():
inventory[i] += 1
else :
inventory[i] = 1
return inventory
inv = {'gol coin':1,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)
输出结果如下:
Inventory:
1 ruby
4 gold coin
1 dagger
1 rope
Total number of items:7