假设所有的子表具有相同的长度,你可以使用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
,无论你喜欢什么),所以你不要把剩下的东西放在地板上。
你确定他们都有相同的长度? –
看看有http://stackoverflow.com/questions/9039961/finding-the-average-of-a-list – mrvol
你可以使用一个循环来处理列表中的元素。 – dsh