平均定义-Python

我有一个清单,里面有一些小清单。每个小清单包含15个元素,因此该平均定义有效。但是,如果我将每个小列表更改为具有不同数量的元素,则此代码显然无法正常工作,无论每个小列表中有多少个元素,我如何都可以对其进行更改?谢谢

def avelist(inputlist):
    total = 0
    for row in inputlist:
        total += sum(row)
    return total/ (15* len(inputlist)
评论
  • 宇智波~
    宇智波~ 回复

    The easiest way is to flatten your nested list and do sum and len directly:

    from itertools import chain
    
    def avelist(inputlist):
        lst = list(chain.from_iterable(inputlist))
        return sum(lst) / len(lst)
    

  • 库破个洞
    库破个洞 回复

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

  • ket
    ket 回复

    只需跟踪项目数:

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