gpt4 book ai didi

python - 这个python函数中的lambda表达式是怎么回事?

转载 作者:太空狗 更新时间:2023-10-30 00:28:53 26 4
gpt4 key购买 nike

<分区>

为什么这种创建柯里化(Currying)函数列表的尝试不起作用?

def p(x, num):
print x, num

def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a

>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test

这是怎么回事?

实际执行我期望上述功能执行的功能是:

import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a


>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test

26 4 0