Python 不相等列表列表的平均值

Python 不相等列表列表的平均值,python,list,mean,Python,List,Mean,我试图得到一个列表,其中包含列表中所有列表中第(I)个元素的平均值。为了进一步解释,如果我有下一个列表: A=[[1,2], [2,3], [1,2,3], [3,4,5], [2,2,1]]. 我想要[a,b,c]和: a = (1+2+1+3+2)/5 b = (2+3+2+4+2)/5 c = (3+5+1)/3 请帮忙 如果您使用的是Python2,则可以尝试使用like so: from itertools import izip_longest from __future__

我试图得到一个列表,其中包含列表中所有列表中第(I)个元素的平均值。为了进一步解释,如果我有下一个列表:

A=[[1,2],  [2,3], [1,2,3], [3,4,5], [2,2,1]].
我想要
[a,b,c]
和:

a = (1+2+1+3+2)/5
b = (2+3+2+4+2)/5
c = (3+5+1)/3
请帮忙

如果您使用的是Python2,则可以尝试使用like so:

from itertools import izip_longest
from __future__ import division

A=[[1,2],  [2,3], [1,2,3], [3,4,5], [2,2,1]]
a,b,c = [sum(filter(None, c))/len(filter(None,c)) for c in izip_longest(*A)]

print a
print b
print c
输出:

1.8
2.6
3.0
用于生成子列表,并计算每组的平均值,忽略
None
s:

from itertools import zip_longest
from statistics import mean

averages = list(map(lambda l: mean(i for i in l if i != None), zip_longest(*A)))
以你的例子:

>>> A = [[1, 2], [2, 3], [1, 2, 3], [3, 4, 5], [2, 2, 1]]
>>> from itertools import zip_longest
>>> from statistics import mean
>>> list(map(lambda l: mean(i for i in l if i != None), zip_longest(*A)))
[1.8, 2.6, 3]

使用
itertools.zip\u
将值压缩在一起。额外的困难在于数据的长度不同
zip_longest
插入
None
作为填充值。我们必须创建一个筛选列表,并仅统计这些项目:

import itertools

A=[[1,2], [2,3], [1,2,3], [3,4,5], [2,2,1]]

tuples = itertools.zip_longest(*A)
for t in tuples:
    s = [x for x in t if x is not None]
    print(sum(s)/len(s))
结果:

1.8
2.6
3.0
编辑:一条线性(可能更复杂,使用
lambda
计算平均值):

结果:
[1.8,2.6,3.0]


(Python 2用户必须用
izip_longest
替换
zip_longest

有趣的是,所有建议的解决方案都是相同的XD您还可以使用列表理解而不是列表映射lambda:
[平均值(如果i!=无)表示zip_longest中的L(*a)]
,并且是shortedStatistics不推荐使用,更改为scipy.statsI后,出现以下错误类型错误:类型为“generator”的对象没有len()@E.Em
statistics
是python内置模块,绝对没有弃用,
scipy
是外部包。另外,我的代码不包含
len
的痕迹,因此您的错误可能来自其他答案之一。起初我认为这是我碰巧拥有的某个外部模块,因为它与anaconda一起提供,但不,它确实是内置的,我在搜索其他东西时发现了它,我立即返回这里给你我的投票XD,我还包括到itPS的链接:zip_不再受支持,改为izip_longest@E.Em:事实正好相反。您正在使用python 2。顺便说一句,你可以接受这个答案。
result = [(lambda x : sum(x)/len(x))([x for x in t if x is not None]) for t in itertools.zip_longest(*A)]