2

I'm trying to create a dict containing several lambda functions. The lambda functions are numpy percentile functions. However I get strange results, as if all lambda functions contain np.percentile(x,q=100).

import numpy as np

d = {}
inc = 10

for i in range(0,101,inc):
    d[str(i)+'_perc'] = lambda x: np.percentile(x,q=i)

a = [1,2,3,4,5]

print(d)
print(d['10_perc'](a))
print(d['50_perc'](a))
print(d['90_perc'](a))

Printing produces:

{'50_perc': <function <lambda> at 0x2cb7b90>, '70_perc': <function <lambda> at 0x2cb77d0>, '40_perc': <function <lambda> at 0x2cb75f0>, '10_perc': <function <lambda> at 0x2cb7cf8>, '30_perc': <function <lambda> at 0x2cb7500>, '0_perc': <function <lambda> at 0x2cb7aa0>, '80_perc': <function <lambda> at 0x2cb78c0>, '20_perc': <function <lambda> at 0x2cb7a28>, '100_perc': <function <lambda> at 0x2cb7848>, '90_perc': <function <lambda> at 0x2cb7758>, '60_perc': <function <lambda> at 0x2cb7d70>}
5
5
5

As if all lambda functions were overwritten by the subsequent function...

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3439329
  • 851
  • 4
  • 10
  • 24

1 Answers1

3

Found a solution:

Something with late bindings that I don't quite understand. Anyways

def returnLambda(i):
    return lambda x: np.percentile(x,i)

for i in xrange(0,101,10): 
    d[str(i)+'_perc'] = returnLambda(i)
    print(i)
user3439329
  • 851
  • 4
  • 10
  • 24
  • good answer for this in https://stackoverflow.com/questions/50298582/why-does-python-asyncio-loop-call-soon-overwrite-data – svs May 11 '18 at 19:21