2017-02-10 106 views
0

我正在做這裏找到的第二個練習。 https://automatetheboringstuff.com/chapter5(「List to Dictionary Function for Fantasy Game Inventory」)將列表中的項目添加到Python中的字典中

任務是將列表中的項目添加到字典中。

由於一些奇怪的原因,我的for循環沒有遍歷整個列表。你能幫我理解爲什麼嗎?

def addToInventory(inventory, addedItems): 
    for i in addedItems: 
     if i in inventory: 
      inventory[i] = inventory[i] + 1 
     else: 
      inventory[i] = 1 
     return inventory 

inv = {'gold coin': 42, 'rope': 1} 
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] 
inv = addToInventory(inv, dragonLoot) 
print(inv) 

當運行該代碼時,結果是「{‘繩’:1‘金幣’:43}」 所以金幣鍵的值被增加1(不是由3,其它應該),而'匕首'和'紅寶石'被忽略。

我在其他地方找到了一個可行的解決方案,但我真的很想理解爲什麼這段代碼不起作用。

在此先感謝。

+1

'回報inventory'是你'for'循環中!它立即返回 –

回答

2
def addToInventory(inventory, addedItems): 
    for i in addedItems: 
     if i in inventory: 
      inventory[i] = inventory[i] + 1 
     else: 
      inventory[i] = 1 
    return inventory 

returnfor後,不經過if。)

+1

我不知道爲什麼這得到了投票;這是正確的答案! –

+2

您已經提供了代碼並顯示了您已更改的內容,但未解釋原因。 (注意:我不是downvoter) – byxor

+1

此外這只是一個錯字。 OP應該知道如何正確縮進代碼。 –

0

的問題是一個簡單的壓痕錯字。現在,如果我們試圖編寫一些更高效的/ pythonic代碼,我們可以使用collections.Counter這是一種計算項目的專用字典類型。您的代碼可以縮短和優化:

from collections import Counter 

inv = Counter({'gold coin': 42, 'rope': 1}) 

inv.update(['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']) 

print(inv) 

結果:

Counter({'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}) 
+0

感謝downvoting試圖改進python編碼的答案。 –

+0

並感謝糾正upvote :) –

+0

謝謝,感謝。 –

相關問題