2011-09-13 59 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]]