it-swarm.cn

迭代与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

谢谢你的帮助。

112
Burton Guster

您可以通过多种方式迭代字典。

如果你遍历字典本身(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)
187
Andrew Clark

您也可以非常轻松地迭代字典:

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)
10
dancek

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

字典对象允许您迭代其项目。此外,通过模式匹配和__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
5
Swiss

列表理解可以缩短事物......

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