在 Python 中迭代对应于 List 的 Dictionary 关键值

使用 Python 2.7。我有一本字典,其中的关键词是球队名称,得分数是每支球队的得分数,值列表是每支球队的得分数:

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

谢谢你的帮助。

261667 次浏览

您也可以非常容易地在字典中进行迭代:

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

对于迭代字典,您有几个选项。

如果您在字典本身(for team in league)上迭代,那么您将在字典的键上迭代。当使用 for 循环进行循环时,无论是在 dict (league)本身还是在 league.keys()上进行循环,其行为都是相同的:

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

您还可以通过遍历 league.items()来一次遍历键和值:

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

您甚至可以在迭代时执行元组解包:

for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)

Dictionary 对象允许您迭代它们的项。另外,使用模式匹配和 __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

列表内涵可以缩短时间。

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