Ivan Shelonik
Ivan Shelonik

Reputation: 2028

Computing mean of all tuple values where 1st number is similar

Consider list of tuples

[(7751, 0.9407466053962708), (6631, 0.03942129), (7751, 0.1235432)]

how to compute mean of all tuple values in pythonic way where 1st number is similar? for example the answer has to be

[(7751, 0.532144902698135), (6631, 0.03942129)]

Upvotes: 2

Views: 146

Answers (3)

Rahul K P
Rahul K P

Reputation: 16081

You do with groupby ,

from itertools import groupby
result = []
for i,g in groupby(sorted(lst),key=lambda x:x[0]):
    grp = list(g)
    result.append((i,sum(i[1] for i in grp)/len(grp)))

Using, list comprehension,

def get_avg(g):
    grp = list(g)
    return sum(i[1] for i in grp)/len(grp)

result = [(i,get_avg(g)) for i,g in groupby(sorted(lst),key=lambda x:x[0])]

Result

[(6631, 0.03942129), (7751, 0.5321449026981354)]

Upvotes: 5

dani herrera
dani herrera

Reputation: 51715

groupby from itertools is your friend:

>>> l=[(7751, 0.9407466053962708), (6631, 0.03942129), (7751, 0.1235432)] 

>>> #importing libs:
>>> from itertools import groupby
>>> from statistics import mean              #(only python >= 3.4)
>>> # mean=lambda l: sum(l) / float(len(l))  #(for python < 3.4) (*1)

>>> #set the key to group and sort and sorting
>>> k=lambda x: x[0]         
>>> data = sorted(l, key=k)  

>>> #here it is, pythonic way:
>>> [ (k, mean([m[1] for m in g ])) for k, g in groupby(data, k) ] 

Results:

[(6631, 0.03942129), (7751, 0.5321449026981354)]

EDITED (*1) Thanks Elmex80s to refer me to mean.

Upvotes: 3

Transhuman
Transhuman

Reputation: 3547

One way is using collections.defaultdict

from collections import defaultdict
lst = [(7751, 0.9407466053962708), (6631, 0.03942129), (7751, 0.1235432)]
d_dict = defaultdict(list)
for k,v in lst:
    d_dict[k].append(v)

[(k,sum(v)/len(v)) for k,v in d_dict.items()]
#[(7751, 0.5321449026981354), (6631, 0.03942129)]

Upvotes: 8

Related Questions