python编程快速上手之第5章实践项目参考答案
1 #!/usr/bin/env python3.5 2 # coding:utf-8 3 # 5.6.1 4 # 好玩游戏的物品清单 5 # 给定一个字典,包含物品名称和数量,并打印出数量对应的物品 6 7 dict_stuff = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12} 8 print("5.6.1参考答案") 9 print('=' * 80) 10 print("给定字典:",dict_stuff) 11 print("运行结果:") 12 def displayInventory(inventory): 13 print("Inventory:") 14 item_total = 0 15 for k,v in inventory.items(): 16 print(str(v) + '\t' + k) 17 item_total += v 18 print("Total number of items:" + str(item_total)) 19 displayInventory(dict_stuff) 20 print('=' * 80) 21 print() 22 # 5.6.2 23 dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby'] 24 print("5.6.2参考答案") 25 print('=' * 80) 26 inv = {'gold coin':42,'rope':1} 27 print("给定列表:",dragonLoot) 28 print("给定字典:",inv) 29 print("运行结果:") 30 def addToInventory(inventory,addedItems): 31 for item in dragonLoot: 32 if item not in inventory.keys(): 33 inventory.setdefault(item,addedItems.count(item)) 34 else: 35 inventory[item] += 1 36 return inventory 37 inv = addToInventory(inv,dragonLoot) 38 print(inv) 39 displayInventory(inv) 40 print('=' * 80)
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16