python编程快速上手-实践项目答案5
作者:互联网
Python编程快速上手第五章课后答案
好玩游戏的物品清单
字典值:
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
写一个名为displayInventory()的函数,它接受任何可能的物品清单,并显示如下:
Inventory
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
代码如下:
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(items):
print('Inventory')
total_num = 0
for k, v in items.items():
print(str(v) + ' ' + k)
total_num += v
print('Total number of items: ' + str(total_num))
displayInventory(stuff)
列表到字典的函数,针对好玩游戏物品清单
写一个名为addToInventory(inventory,addedItems)的函数,其中inventory参数是一个字典,表示玩家的物品清单,addedItems参数是一个列表。
addToInventory()函数应该返回一个字典,表示更新过的物品清单。请注意,列表可以包含多个一样的项。
输出应如下:
Inventory
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
代码如下:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(items):
print('Inventory')
total_num = 0
for k, v in items.items():
print(str(v) + ' ' + k)
total_num += v
print('Total number of items: ' + str(total_num))
def addToInventory(inventory, addedItem):
for i in addedItem:
if i in inventory:
inventory[i] += 1
else:
inventory[i] = 1
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
标签:dagger,gold,python,items,编程,num,inventory,上手,coin 来源: https://blog.csdn.net/Jrieh/article/details/113379357