游戏一
你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物品。例如,字典值{‘rope’: 1, ‘torch’: 6, ‘gold coin’: 42, ‘dagger’: 1, ‘arrow’: 12}意味着玩家有 1 条绳索、6 个火把、42 枚金币等。将其打印出来
def displayInventory(materials):
count = 0
for material in materials.keys():
print(material + ' ' + str(materials[material]))
count += materials[material]
print("Inventory:", end='\n')
print("Total number of items:%d"%count)
# ------------------------实例------------------------------
stuffs ={'rope':1, 'torch':6, 'gold coin':42, 'dagger':1, 'arrow':12}
displayInventory(stuffs)
Inventory:
rope 1
torch 6
gold coin 42
dagger 1
arrow 12
Total number of items:62
游戏二
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
写一个名为 addToInventory(inventory, addedItems)的函数,其中 inventory 参数
是一个字典,表示玩家的物品清单(像前面项目一样),addedItems 参数是一个列表,就像 dragonLoot。addToInventory()函数应该返回一个字典,表示更新过的物品清单。请注意,列表可以包含多个同样的项。
def addToInventory(inventory, addedItems):
count = 0
for item in addedItems:
if item not in inventory:
inventory[item] = 0
inventory[item] += 1
count += inventory[item]
print("Inventory:", end='\n')
for key in inventory.keys():
print(str(inventory[key]) + ' ' + key)
print("Total number of items:%d"%count)
# ------------------实例-----------------------
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
addToInventory(inv, dragonLoot)
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items:134
>>>