related lists mean value (golfed)

Michael Rudolf spamfresser at ch3ka.de
Tue Mar 9 06:11:35 EST 2010


OK, I golfed it :D
Go ahead and kill me ;)

x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

def f(a,b,v={}):
     try: v[a].append(b)
     except: v[a]=[b]
     def g(a): return sum(v[a])/len(v[a])
     return g
w = [g(i) for g,i in [(f(i,v),i) for i,v in zip(y,x)]]

print("w is now the list of averages, corresponding with y:\n \
         \n x: %s \n y: %s \n w: %s \n" % (x, y, w))

Output:
w is now the list of averages, corresponding with y:

  x: [1, 2, 8, 5, 0, 7]
  y: ['a', 'a', 'b', 'c', 'c', 'c']
  w: [1.5, 1.5, 8.0, 4.0, 4.0, 4.0]

Regards,
Michael



More information about the Python-list mailing list