2017-03-25 52 views
0

因此,我想統計所有的值,使totalItems var將被打印在列表下面。輸出給了我5而不是全部反擊。有人能解釋我爲什麼,而不僅僅是給出正確的代碼。Python count在字典中的總項目

stuff = {'coins': 5, 'arrows': 42, 'rope': 1} 


def getInvent(inventory): 

    itemTotal = 0 
    print('Inventory:') 
    print(str(stuff['coins']) + ' Coins') 
    print(str(stuff['arrows']) + ' Arrows') 
    print(str(stuff['rope']) + ' Rope') 

    for k, v in stuff.items(): 
     itemTotal = itemTotal + v 
     print('Total number of items: ' + str(itemTotal)) 
     return itemTotal 

getInvent(stuff) 
+0

你讀過的代碼並遵循它做什麼? –

+0

您的代碼存在縮進問題。 'return itemTotal'在for循環中,因此在第一次迭代之後'5'被返回並且不計數。一個簡單的代碼將是 - 'sum(stuff.values())'。 –

回答

1

你不應該return你的循環中,因爲它會立即返回那種情況下(在循環的第一次迭代)。相反,把回報放在循環之外。

for k, v in stuff.items(): 
    itemTotal = itemTotal + v 
    print('Total number of items: ' + str(itemTotal)) 
return itemTotal 

函數將在遇到return語句時立即返回。所以你應該確保你的循環在返回值之前全部運行。

+0

我甚至沒有注意到它!非常感謝。這正是我所搜索的! – Mees

2

您可以sum()dict.values()轉用於循環到一個班輪:

>>> sum(stuff.values()) 
48 

說明:

stuff.values()讓你在字典中的所有值的列表:

>>> stuff.values() 
[1, 5, 42] 

sum()加在一起al在一個迭代(如表)損益項目:

>>> sum([1, 5, 42]) 
48 

完整的示例:

stuff = {'coins': 5, 'arrows': 42, 'rope': 1} 

def getInvent(inventory): 
    print('Inventory:') 
    print(str(stuff['coins']) + ' Coins') 
    print(str(stuff['arrows']) + ' Arrows') 
    print(str(stuff['rope']) + ' Rope') 

    itemTotal = sum(inventory.values()) 
    print('Total number of items: ' + str(itemTotal)) 
    return itemTotal 

getInvent(stuff) 
+0

Julien剛剛打敗了我,總結了值的列表是最簡單的方法在一個可讀的代碼行中執行此操作 –

+0

謝謝,並且我看到了關於stackoverflow上sum()的一些信息,但事實是,我是遵循一本書的規則。規則是不使用sum(),因爲我還沒有能夠學習。 – Mees