我的代码为什么不返回字典的平均值?

时间:2019-11-04 23:05:28

标签: python dictionary average


    >>> get_average_club_count(P2C)
    1.6
    """
    average = 0
    summ = 0
    for key in person_to_clubs:
        summ = sum + len(person_to_clubs[key])
    average = sum / len(person_to_clubs)

我正在使用的字典:


当我尝试执行docstring示例时得到的回报:

    summ = sum + len(person_to_clubs[key])
builtins.TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int'

2 个答案:

答案 0 :(得分:1)

sum是一个内置函数,因此不能将其用作变量名。命名summ也不是一个很好的解决方法,因为您容易混淆自己(就像我认为的那样)。也许total

total = 0.0
for person in person_to_clubs:
    total += len(person_to_clubs[person])
return total / len(person_to_clubs)

答案 1 :(得分:0)

我相信您在变量名中缺少了一个“ m”!

我会说正确的代码是:

def get_average_club_count(person_to_clubs: Dict[str, List[str]]) -> float:
    """Return the average number of clubs that a person in person_to_clubs
    belongs to.

    >>> get_average_club_count(P2C)
    1.6
    """
    average = 0
    summ = 0
    for key in person_to_clubs:
        summ = summ + len(person_to_clubs[key])
    average = summ / len(person_to_clubs)

错误来自以下事实:sum是Python中的内置函数,而summ是您定义的局部变量。