Python:查找嵌套列表的平均值

Bru*_*uce 13 python

我有一份清单

a = [[1,2,3],[4,5,6],[7,8,9]]
Run Code Online (Sandbox Code Playgroud)

现在我想找到这些内部列表的平均值

a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3]
Run Code Online (Sandbox Code Playgroud)

'a'最后不应该是嵌套列表.请为一般案例提供答案

Alo*_*hal 12

a = [sum(x)/len(x) for x in zip(*a)]
# a is now [4, 5, 6] for your example
Run Code Online (Sandbox Code Playgroud)

在Python 2.x中,如果您不想要整数除法,请sum(x)/len(x)1.0*sum(x)/len(x)上面替换.

拉链文档.


YOU*_*YOU 5

>>> import itertools
>>> [sum(x)/len(x) for x in itertools.izip(*a)]
[4, 5, 6]
Run Code Online (Sandbox Code Playgroud)


tel*_*t99 5

如果您安装了numpy

>>> import numpy as np
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> arr = np.array(a)
>>> arr
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.mean(arr)
5.0
>>> np.mean(arr,axis=0)
array([ 4.,  5.,  6.])
>>> np.mean(arr,axis=1)
array([ 2.,  5.,  8.])
Run Code Online (Sandbox Code Playgroud)