2015-12-21 53 views
0

我在某种程度上卡住了,并希望得到一些有用的指针。列表的变量列表中的平均元素

我不知道提前列表[X]的长度;即子列表的数量[y1,y2,y3,...,yn]。

我怎么能每个元素上工作,从各子列表作为位置的功能?

即,

Z1 = AVG(Y1 [1] + Y2 [1] +,...,+ Y [1] n)的

Z2 = AVG(Y1 [2] + y2 [2] +,...,+ y [2] n)

Z3 = avg(y1 [3] + y2 [3] +,...,+ y [3] n)

的Zm = AVG(Y1 [M] + Y2 [M] +,...,+ Y [M] n)的

任何输入是极大的赞赏,

马库斯

+0

你确定他们都有相同的长度? –

+2

看看有http://stackoverflow.com/questions/9039961/finding-the-average-of-a-list – mrvol

+0

你可以使用一个循环来处理列表中的元素。 – dsh

回答

0

假设所有的子表具有相同的长度,你可以使用zip轻松地做到这一点:

ally = [...] 
averages = [sum(suby)/len(suby) for suby in zip(*ally)] 

zip(*ally)有效转换[[a1, a2, ...], [b1, b2, ...]]tuple s的(a1, b1),(a2, b2)等等,所以Python的工作就是为每个子列表匹配你的值。

如果你想处理,其中子列表的长度不匹配(例如,[[a1, a2], [b1, b2, b3]])的情况下,这将是更加复杂;你需要(Python的2 izip_longest)使用itertools.zip_longest并过滤掉垃圾条目,以避免包括他们在平均:

from itertools import zip_longest 

# zip_longest matches up values until last value exhausted 
# with shorter sequences substituting in None 
# We then use the generator expression to remove the Nones 
stripped = ([y for y in suby if y is not None] for suby in zip_longest(*ally)) 
# Then average as normal 
averages = [sum(suby)/len(suby) for suby in stripped] 

如果你想治疗太短子list S作为0(所以他们“会降低平均),这是简单的:

averages = [sum(suby)/len(suby) for suby in zip_longest(*ally, fillvalue=0)] 

其中fillvalue可根据需要改变一些其他的默认值。

注:如果这是Python 2中的代码,sum(suby)/len(suby)将使用舍去除法如果所有的值都int/long;如果你想真正的分裂,要么添加from __future__ import division到文件的顶部(或在您的解释器中运行它),在默认情况下得到PY3真司(使用//地板师),或包裹在float()构造的len(suby)(或乘以通过1.0,无论你喜欢什么),所以你不要把剩下的东西放在地板上。