假設所有的子表具有相同的長度,你可以使用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