在Python中迭代与List对应的字典键值

在Python 2.7中工作。 我有一个以球队名字作为关键字的字典,以及每个球队获得的进球数量作为价值清单:

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 

谢谢你的帮助。

你有几个迭代字典的选项。

如果你迭代字典本身( for team in league ),你将迭代字典的键。 循环使用for循环时,无论循环使用dict( league )本身, 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) 

你也可以很容易地迭代字典:

 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) 

字典有一个名为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 

字典对象允许你迭代他们的项目。 另外,通过模式匹配和__future__的划分,你可以简化一些事情。

最后,您可以将您的逻辑从打印中分离出来,以便稍后重构/debugging。

 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 

列表理解可以缩短事情…

 win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]