我有一个由一些小列表组成的列表。每个小列表由15个元素组成,因此这个平均定义是有效的。然而,如果我改变了每个小列表的元素数量,这个代码显然不能工作,我如何改变它,使它在每个小列表中有多少个元素都能工作呢?谢谢
def avelist(inputlist):
total = 0
for row in inputlist:
total += sum(row)
return total/ (15* len(inputlist)发布于 2020-05-18 12:15:58
只需跟踪项目的数量:
def avelist(inputlist):
total = 0
items = 0
for row in inputlist:
total += sum(row)
items += len(row)
return total / items发布于 2020-05-18 12:16:35
最简单的方法是扁平化嵌套列表,并直接执行sum和len:
from itertools import chain
def avelist(inputlist):
lst = list(chain.from_iterable(inputlist))
return sum(lst) / len(lst)发布于 2020-05-18 12:16:10
def avelist(inputlist):
total = 0
totallen = 0
for row in inputlist:
total += sum(row)
totallen += len(row)
return total/ totallenhttps://stackoverflow.com/questions/61862326
复制相似问题