I try to get a list that include the mean of all of (i)th element in all lists of a list.To explain more, if i have the next list:
A=[[1,2], [2,3], [1,2,3], [3,4,5], [2,2,1]].
I want to have [a,b,c]
with:
a = (1+2+1+3+2)/5
b = (2+3+2+4+2)/5
c = (3+5+1)/3
Any help please!
use itertools.zip_longest
to zip values together. The extra difficulty is that the length of the data varies. zip_longest
inserts None
as a fill value. We have to create a filtered list, and count only those items:
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))
result:
1.8
2.6
3.0
EDIT: one-liner (maybe a bit more complex, using lambda
to compute mean):
result = [(lambda x : sum(x)/len(x))([x for x in t if x is not None]) for t in itertools.zip_longest(*A)]
result: [1.8, 2.6, 3.0]
(Python 2 users have to replace zip_longest
by izip_longest
)
You can try with itertools.izip_longest()
like so if you are on Python2:
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
Output:
1.8
2.6
3.0
Use itertools.zip_longest
to generate the sublists, and statistics.mean
to calculate the average for each group, disregarding the 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)))
With your example:
>>> 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.