【问题标题】:Subtracting by Dictionary Values from Iterated Total in For Loop Python在For循环Python中从迭代总计中减去字典值
【发布时间】:2011-11-19 13:11:47
【问题描述】:

在 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 运行?

感谢您的帮助!

【问题讨论】:

    标签: python list dictionary iteration subtraction


    【解决方案1】:

    如果您想要字典中每个团队的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']
    

    【讨论】:

    • 我还是有同样的问题。因为 total_runs_scored 尚未存储,所以对于第一支球队,该函数返回 0,因为它从 total_runs_scored 中减去第一支球队的总数,此时只包含第一支球队的总数。不过,感谢您的帮助。
    • 在你写的代码后面加上我写的代码,这样你就有了两个for循环。见pastebin of full code
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2020-02-20
    相关资源
    最近更新 更多