如何在Python3中使用sum函数

时间:2019-06-12 20:51:33

标签: python

我试图一次又一次地使用sum函数,但是我一直收到错误消息。我写了以下代码:

averages["averages_home_goals"] = sum(d['home_goals'] for d in averages.values() if d)
averages["averages_away_goals"] = sum(d['away_goals'] for d in averages.values() if d)
averages["averages_home_conceded"] = sum(d['home_conceded'] for d in averages.values() if d)
averages["averages_away_conceded"] = sum(d['away_conceded'] for d in averages.values() if d)

print(averages)

平均值变量如下所示:

{
    'Belconnen%20United': {
        'home_goals': 4.0,
        'away_goals': 1.0,
        'home_conceded': 0.0,
        'away_conceded': 2.1666666666666665,
    },
    'Canberra%20FC': {
        'home_goals': 1.75,
        'away_goals': 1.8,
        'home_conceded': 2.0,
        'away_conceded': 2.0,
    },
    # More data of a similar structure
}

运行此命令时,出现以下错误:

TypeError: 'float' object is not subscriptable

奇怪的是;当我只运行这4行中的一行时,代码可以正常执行(无论哪一行都行)。执行averages["averages_away_goals"] = ...语句时出现错误

有人可以帮我吗?为变量d指定另一个名称也不起作用

1 个答案:

答案 0 :(得分:6)

第一行将正常工作,但是失败将从第二行开始并继续。原因是您在第一行之后的averages词典中包含了一个新条目。因此,您的averages字典具有一个具有单个浮点值的新键"averages_home_goals"

执行第二行时,您将遍历字典averages的所有值,该字典现在具有键"averages_home_goals"中所有本垒球总和的附加值,这将继续成为一个浮动。而且您不能下标浮点数。基本上,这意味着您试图执行以下类型的代码示例(在第二行):

12.3242["away_goals"]

将始终失败。

作为解决方案,我建议将结果存储到新字典中,例如。

res = {}

res["averages_home_goals"] = sum(d['home_goals'] for d in averages.values() if d)
res["averages_away_goals"] = sum(d['away_goals'] for d in averages.values() if d)
res["averages_home_conceded"] = sum(d['home_conceded'] for d in averages.values() if d)
res["averages_away_conceded"] = sum(d['away_conceded'] for d in averages.values() if d)

print(res)