2011-09-13 11 views
88

Python 2.7での作業。私は関数に辞書を供給できるようにしたいと、それぞれを反復処理でしょうPythonのリストに対応するディクショナリキー値の繰り返し

NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]} 

:私は、キーと値のリストとして各チームの得点と許さ実行の量としてチーム名の辞書を持っていますチーム(キー)。

ここに私が使用しているコードがあります。今はチームでしか行けません。どのように各チームを反復して、各チームの期待される勝利率をプリントするのですか?

def Pythag(league): 
    runs_scored = float(league['Phillies'][0]) 
    runs_allowed = float(league['Phillies'][1]) 
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000) 
    print win_percentage 

ありがとうございました。

+1

'dic.items()' ...助けを – JBernardo

答えて

141

あなたは辞書を反復処理するためのいくつかのオプションがあります。

辞書自体(for team in league)を反復処理すると、辞書のキーを反復処理します。 forループを使用してループすると、dict()自体をループするかどうかにかかわらず、動作は同じleague.keys()またはleague.iterkeys()と同じになります。それが明示的かつ効率的であるため、dict.iterkeys()は、一般的に好ましい:

for team in league.iterkeys(): 
    runs_scored, runs_allowed = map(float, league[team]) 

ます。またleague.items()league.iteritems()を反復することにより、一度にキーと値の両方を反復処理することができます

for team, runs in league.iteritems(): 
    runs_scored, runs_allowed = map(float, runs) 

あなたも、あなたを行うことができます反復処理中にタプルを展開する:

for team, (runs_scored, runs_allowed) in league.iteritems(): 
    runs_scored = float(runs_scored) 
    runs_allowed = float(runs_allowed) 
+28

dict.iteritems()はPython3以降に削除されました。代わりにdict.items()を使うべきです – Sergey

+11

dict.iterkeys()もPython 3では削除されました。代わりにdict.keys()を使うべきです – Nerrve

8

あなたは非常に簡単に、あまりにも、辞書を反復処理することができます

for team, scores in NL_East.iteritems(): 
    runs_scored = float(scores[0]) 
    runs_allowed = float(scores[1]) 
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000) 
    print '%s: %.1f%%' % (team, win_percentage) 
+0

ありがとう!コードはうまくいった。 –

+0

@BurtonGuster:あなたが答える価値があると思うときはいつでも、アップポットしてください(ポストの左側にある "up"ボタンをクリックしてください)!あなたがコミュニティを手助けしているようにも! – dancek

5

辞書はiterkeys()と呼ばれる機能が組み込まれています。

試してみてください。

for team in league.iterkeys(): 
    runs_scored = float(league[team][0]) 
    runs_allowed = float(league[team][1]) 
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000) 
    print win_percentage 
+0

助けてくれてありがとう! –

4

ディクショナリオブジェクトを使用すると、アイテムを反復処理できます。また、パターンマッチングと__future__からの分割では、少し単純化することができます。

最後に、ロジックを印刷から分離して、後でリファクタリング/デバッグするのを少し容易にすることができます。

from __future__ import division 

def Pythag(league): 
    def win_percentages(): 
     for team, (runs_scored, runs_allowed) in league.iteritems(): 
      win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000) 
      yield win_percentage 

    for win_percentage in win_percentages(): 
     print win_percentage 
2

一覧物事を短縮することができます理解...

win_percentages = [m**2.0/(m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]] 
関連する問題