1、创建一个字典,其中键是字符串,描述一个物品,值是一个整型值,说明有多少该物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味着有 1 条绳索、 6 个火把、 42 枚金币等。
2、写一个名为 displayInventory()的函数,显示出字典中所有物品及其数量,并统计出总数量
3、
写一个名为 addToInventory(inventory, addedItems)的函数, 其中 inventory 参数是一个字典, 存储物品清单, addedItems 参数是一个列表,存储需要更新的物品。addToInventory()函数应该返回一个字典,表示更新过后的物品清单。
代码一:
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*-
3 #打印字典
4 def displayInventory(inventory):
5 print 'Inventory:'
6 item_total=0
7 for k,v in inventory.items():
8 print str(v)+' '+k
9 item_total+=v
10 print 'Total number of items:'+str(item_total)
11 #列表添加到字典
12 def addToInventory(inventory,addItems):
13 for k in addItems:
14 if k in inventory.keys():
15 inventory[k]+=1
16 else:
17 inventory[k]=1
18 return inventory
19
20 #初始字典
21 inv={'gold coin':42,'rope':1}
22 #需要添加的列表
23 dragonLoot=['gold coin','dagger','gold coin','gold coin','ruby']
24 #将列表添加到字典
25 inv=addToInventory(inv,dragonLoot)
26 #显示更新后的字典
27 displayInventory(inv)
显示结果:
代码二(实现同样功能):
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*-
3 def displayInventory(inven):
4 print "Inventory:"
5 item_total=0
6 for k,v in inven.items():
7 print str(v)+" "+k
8 item_total+=v
9 print "Total number of the items: "+str(item_total)
10
11 def addListToInventory(inven,addedItems):
12 for i in range(len(addedItems)):
13 if addedItems[i] in inven.keys():
14 inven[addedItems[i]]+=1
15 else:
16 inven.setdefault(addedItems[i],1)
17 return inv
18 inv={'gold coin':42,'rope':1}
19 addedList=['gold coin','dagger','gold coin','gold coin','ruby']
20 inv=addListToInventory(inv,addedList)
21 displayInventory(inv)
运行结果: