2011-09-13 60 views
88

使用Python 2.7。我與球隊的名字作爲鍵和運行的得分並允許每隊作爲值列表量的字典:迭代Python字典中對應於列表的鍵值

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

我想能夠養活字典成一個函數和遍歷每個團隊(關鍵)。

這是我正在使用的代碼。現在,我只能一起去團隊。我將如何迭代每個團隊併爲每個團隊打印預期的win_percentage?

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循環循環時,無論循環使用字典()本身,league.keys()還是league.iterkeys(),行爲都將保持不變。 dict.iterkeys()一般是可取的,因爲它是明確的,高效:

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

你甚至可以執行你:

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

您也可以一次通過遍歷league.items()league.iteritems()遍歷兩個鍵和值迭代時解開元組:

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:每當你想到一個值得回答的問題時,請點擊upvote(點擊帖子左側的「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]]