2011-09-17 4 views
1

私はPython 2.7で作業しています。キーで辞書がリストに対応するときの最初の値の集計(Python)

NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]} 

リストの最初の値は、実行の量は、チームが持っている得点であり、第二は、そのチームはあきらめたランの量である:私は、次の辞書のチームのリストを持っています。

私はこのコードを使用して各チームのピタゴラスの勝率を決定していますが、グループ全体で得点され、許可された合計ラン数を計算する機能を持つこともできます。

今私が使用している:

Pythag(league): 
    for team, scores in league.iteritems(): 
    runs_scored = float(scores[0]) 
    runs_allowed = float(scores[1]) 
    win_percentage = (runs_scored**2)/((runs_scored**2)+(runs_allowed**2)) 
    total_runs_scored = sum(scores[0] for team in league) 
    print '%s: %f' % (team, win_percentage) 
    print '%s: %f' % ('League Total:', total_runs_scored) 

を私はSUM関数で起こっている正確に何わからないんだけど、代わりに一つの値を得るための、私は各反復の上に別の値を取得していますチームとwin_percentageの値は同じではなく、同じ値ではありません。

理想的には、関数はディクショナリ内の各チームの得点ランの合計に対して1つの値を返します。

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

+0

コードを簡略化するために['namedtuple'](http://docs.python.org/library/collections.html#collections.namedtuple)を使用することができます。' NL = {team:チームの実行(*スコア) 、NL.iteritems()のスコア '' Run = collections.namedtuple( 'Run'、 'scored allowed') 'となります。 – jfs

+0

@ JFS 'for team、(得点、許可)in league.iteritems():' – agf

+0

@agf:NLが1回だけ使用されるかどうかを確認してください。 – jfs

答えて

3

使用可能な実行中の合計を持ちたい、またはあなたが行うことができ、二回を反復処理したくない場合は、次の

def Pythag(league): 
    total_runs_scored = 0 
    for team, scores in league.iteritems(): 
     # other stuff 
     total_runs_scored += scores[0] 
     # other stuff 
     # runs scored by all teams up to this point 
     print 'League Running Total of Runs Scored: %f' % (total_runs_scored,) 
    # outside the loop, so total runs scored in the league. 
    # will be the same as the last one in the loop 
    print 'League Total Runs Scored: %f' % (total_runs_scored,) 

は、ループ内で使用すると、およそ単一チームを話していることを覚えておいてくださいあなたが実行を取得するためにsumを行う必要はありませんので、、そのチームでを獲得し、あなたの代わりに、つまり、以前のすべてのチームを獲得し実行に追加するには、以前の反復からのscores[0]を必要としますループの

+0

これはおそらく最も効率的です。 –

関連する問題