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 23 # 5.6.2 24 # 將給定的列表添加到字典中去,並統計相同鍵對應的數量,最后統計總字典中值的總數 25 dragonLoot = ['gold coin','dagger','dagger','gold coin','gold coin','ruby','ruby'] 26 27 print("5.6.2參考答案") 28 print('=' * 80) 29 inv = {'gold coin':42,'rope':1} 30 print("給定列表:",dragonLoot) 31 print("給定字典:",inv) 32 print("運行結果:") 33 34 # 按照SWI的思路,這里可以2種方法: 35 # 1是將列表轉換成字典再操作 36 # 2是用setdefault方法將列表元素加到字典再進行元素個數的自增 37 # 在此感謝SWI的指點斧正。 38 39 def addToInventory(inventory,addedItems): 40 for item in addedItems: 41 inventory.setdefault(item,0) 42 inventory[item] += 1 43 return inventory 44 inv = addToInventory(inv,dragonLoot) 45 print(inv) 46 displayInventory(inv) 47 print('=' * 80)
程序運行結果如下:
(py35env) frank@ThinkPad:py_fas$ python dict_inventory-5.py
5.6.1參考答案
================================================================================
給定字典: {'arrow': 12, 'gold coin': 42, 'dagger': 1, 'rope': 1, 'torch': 6}
運行結果:
Inventory:
12 arrow
42 gold coin
1 dagger
1 rope
6 torch
Total number of items:62
================================================================================
5.6.2參考答案
================================================================================
給定列表: ['gold coin', 'dagger', 'dagger', 'gold coin', 'gold coin', 'ruby', 'ruby']
給定字典: {'rope': 1, 'gold coin': 42}
運行結果:
{'ruby': 2, 'dagger': 2, 'rope': 1, 'gold coin': 45}
Inventory:
2 ruby
2 dagger
1 rope
45 gold coin
Total number of items:50
================================================================================