3 回答
TA贡献1784条经验 获得超2个赞
您可以sum计算内部列表的总和:
x = [[1,3,2],[4,5,6],[7,8,9]]
s = sum(sum(a) for a in x)
l = sum(len(a) for a in x)
print(s / l) # 5.0
TA贡献1895条经验 获得超7个赞
这为您提供了列表列表的平均值以及完整列表的平均值。
x = [[1,3,2],[4,5,6],[7,8,9]]
new_list = [sum(l)/len(l) for l in x]
print(sum(new_list)/len(new_list))
输出:
5.0
TA贡献1757条经验 获得超7个赞
一个更学术的方法是:
x = [[1,3,2],[4,5,6],[7,8,9]]
#stripping square brackets
elementsString = ''.join( c for c in str(x) if c not in '[]' )
total = 0
numberOfElements = 0
#converting the string numbers into int
for i in elementsString.split(','):
#using int but can be also float for example
i = int(i)
numberOfElements += 1
total += i
average = total/numberOfElements
print(average)
#5.0 is the answer in your case
添加回答
举报