2017-03-23 3 views
-6

用で追加の結果、私はそれぞれの在庫値を追加し、新しい合計を印刷したい:Pythonの:ループ

prices = { 
    "banana" : 4, 
    "apple" : 2, 
    "orange" : 1.5, 
    "pear" : 3, 
} 
stock = { 
    "banana" : 6, 
    "apple" : 0, 
    "orange" : 32, 
    "pear" : 15, 
} 



for key in prices: 
    total = 0 
    inventory = (prices[key] * stock[key]) 
    print key 
    print "inventory value: %s" % (inventory) 
    total = total + inventory 

print total 
+5

は、 'total = 0'をあなたのforループに置くか、毎回リセットされます。 –

+0

「コレクション」からかなりのカウンターを使用する:「カウンター(価格)+カウンター(株)」 –

+0

http://www.codeskulptor.org/#user42_IuCPcQKD20_0.py – Hackerman

答えて

1

移動合計= 0サイドアウトループ

prices = { 
    "banana" : 4, 
    "apple" : 2, 
    "orange" : 1.5, 
    "pear" : 3, 
} 
stock = { 
    "banana" : 6, 
    "apple" : 0, 
    "orange" : 32, 
    "pear" : 15, 
} 


total = 0 
for key in prices: 
    inventory = (prices[key] * stock[key]) 
    print key 
    print "inventory value: %s" % (inventory) 
    total = total + inventory 

print total 
+0

ありがとうございます。これは働いた – love2code1975

1

あなたのエラーはあなたがすべての繰り返しでtotalをリセットすることです。

あなたは問題のこれらの種類のための適切な制御フローを確保内包表記を使用することによって、エラーのこれらの種類を避けることができます:

total = sum(p * stock.get(key,0) for key,p in prices.items()) 

それは、古典的なループよりもはるかに高速である(とキーとアイテムの両方に反復すると節約最後のボーナス価格アイテム)となどのアクセス:在庫切れのTFのアイテムは、クラッシュしませんが、利回り0

+0

これもうまくいき、私は初期合計変数を0に設定します。 – love2code1975

+0

forループの外側に 'total = 0'を配置するという単純なソリューションとは対照的に、この方法を使用する利点は何ですか? – love2code1975

+0

そのpythonic - その簡潔を意味する – bvmcode