我试图创建一个包含几个lambda函数的dict。 lambda函数是numpy百分位函数。但是我得到了奇怪的结果,好像所有lambda函数都包含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))
印刷产生:
{'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
好像所有lambda函数都被后续函数覆盖了......
答案 0 :(得分:1)
找到解决方案:
后期绑定的东西,我不太明白。反正
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)