[英]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)
。
>>> import itertools
>>> [sum(x)/len(x) for x in itertools.izip(*a)]
[4, 5, 6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.