开发者

list of python lambda functions w/o partial

开发者 https://www.devze.com 2023-03-12 17:49 出处:网络
I have been trying to generate a list of lambda functions in python using list comprehension. but it didn\'t work,

I have been trying to generate a list of lambda functions in python using list comprehension. but it didn't work,

for example

fl=[lambda x: x**i for i in range(5)]

i have check the other question, it basically generate the same function based on the reference of i.

so I also tried partial.

from functools im开发者_如何转开发port partial

fl=[partial(lambda x: x**i) for i in range(5)]

but it didn't work too. any help will be appreciated. cheers~


You're tripping over Python scopes.

fl=[lambda x, i=i: x**i for i in range(5)]


You're effectively passing i in by name.

fl=[lambda x: x**i for i in range(5)]

Every time lambda is executed, it binds the same i to the function, so when the function is executed (later) it uses the then-current value of i (which will be 4). You should pass it in as a default argument instead:

fl=[lambda x, j=i: x**j for i in range(5)]

Actually, I noticed that you're misusing partial. Here:

fl = [partial(lambda x, y: y ** x, i) for i in range(5)]

That works as well.


Another common workaround is to use a closure:

def create_f(i):
    def f(x):
        return x**i
    return f

fl = [create_f(i) for i in range(5)]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号