首页 > 解决方案 > 平均定义 - Python

问题描述

我有一个由里面的小列表组成的列表。每个小列表由 15 个元素组成,因此这个平均定义有效。但是,如果我将每个小列表更改为具有不同数量的元素,则此代码显然不起作用,我如何更改它以使其无论每个小列表中有多少元素都可以工作?谢谢

def avelist(inputlist):
    total = 0
    for row in inputlist:
        total += sum(row)
    return total/ (15* len(inputlist)

标签: python

解决方案


只需跟踪项目的数量:

def avelist(inputlist):
    total = 0
    items = 0

    for row in inputlist:
        total += sum(row)
        items += len(row)

    return total / items

推荐阅读