python實踐項目三:將列表添加到字典


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)

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM