related lists mean value (golfed)

Peter Otten __peter__ at web.de
Tue Mar 9 07:02:12 EST 2010


Michael Rudolf wrote:

> 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]

>>> [sum(a for a,b in zip(x,y) if b==c)/y.count(c)for c in y]
[1.5, 1.5, 8.0, 4.0, 4.0, 4.0]

Peter



More information about the Python-list mailing list