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

时间:2010-01-28 09:27:30

标签: python

我有一个清单

a = [[1,2,3],[4,5,6],[7,8,9]]

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

a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3]

'a'最后不应该是嵌套列表。请为通用案例提供答案

3 个答案:

答案 0 :(得分:11)

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

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

Documentation for zip

答案 1 :(得分:5)

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

答案 2 :(得分: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.])