How to find mean of an array which has two elements in Python?

  • A+

I need to find mean of an array which is like: [('a', 5), ('b', 2), ('a', 4), ('b', 6)]

Result should be like; [('a', 4.5), ('b', 4)]


Raw solution without additional libraries could look like this:

def mean(l):     result = {}     for key, value in l:         if key not in result:             result[key] = []         result[key].append(value)      return [(k, sum(v)/len(v)) for k, v in result.items()]  lst = [('a', 5), ('b', 2), ('a', 4), ('b', 6)] m = mean(lst)  print(m) # [('a', 4.5), ('b', 4.0)] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: