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
================================================================================