在For循环Python中通过字典值从Iterated Total中减去

时间:2011-09-18 05:05:12

标签: python list dictionary iteration subtraction

使用Python 2.7。

我有一个字典,团队名称作为键,值包含在列表中。第一个值是团队得分的运行量,第二个值是允许的运行:

NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]}

我有一个迭代每个键的函数,并提供整个字典得分和允许的总运行。我还希望能够从总数中减去每个团队,并创建联盟减去团队价值。

我首先尝试了以下方面:

def Tlog5(league, league_code):
    total_runs_scored = 0
    total_runs_allowed = 0
    for team, scores in league.iteritems():
        total_runs_scored += float(scores[0])
        total_runs_allowed += float(scores[1])
        team_removed_runs = total_runs_scored - scores[0]

不幸的是,这似乎只从已经迭代的值中减去而不是从完全总数中减去。因此,对于字典中的第一个团队,team_removed_runs为0,对于第二个团队,它是前两个团队减去第二个团队总数的总计(仅留下第一个团队总数。

我尝试将team_removed_runs = total_runs_scored - scores [0]移出for循环,但后来我只得到了字典中最后一个团队的值。

有没有办法可以为字典中的所有团队返回team_removed运行?

感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

如果您想要字典中每个团队的team_removed_runs,您需要返回字典并计算总运行次数减去每个团队的运行次数。像

这样的东西
team_removed_runs = {}
for team, scores in league.iteritems():
    team_removed_runs[team] = [total_runs_scored - scores[0],
                               total_runs_allowed - scores[1]]

这将为整个联盟使用total_runs_scoredtotal_runs_allowed的最终值,然后从该总数中减去每个球队的值,并将结果存储在字典team_removed_runs中。因此,如果你希望联盟总价值低于费城人队,你可以在

找到
team_removed_runs['Phillies']