简体   繁体   English

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

[英]Python: Finding average of a nested list

I have a list 我有一份清单

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

Now I want to find the average of these inner list so that 现在我想找到这些内部列表的平均值

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

'a' should not be a nested list in the end. 'a'最后不应该是嵌套列表。 Kindly provide an answer for the generic case 请为一般案例提供答案

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

In Python 2.x, if you don't want integer division, replace sum(x)/len(x) by 1.0*sum(x)/len(x) above. 在Python 2.x中,如果您不想要整数除法,请将sum(x)/len(x)替换为上面的1.0*sum(x)/len(x)

Documentation for zip . 拉链文档

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

If you have numpy installed: 如果您安装了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.])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM