在Python中遍历与List对应的Dictionary键值

2024-04-24 03:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.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

谢谢你的帮助。


Tags: 名称列表字典runs关键字float团队次数
3条回答

有几个选项可用于遍历字典。

如果遍历字典本身(for team in league),则将遍历字典的键。当使用for循环时,无论是循环dict(league)本身,还是循环^{},行为都将相同:

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)

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

相关问题 更多 >