How does a lambda function refer to its parameters in python?

前端 未结 4 1739
余生分开走
余生分开走 2021-01-05 17:09

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like

fs = [         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 17:44

    1. The variable i is local to the list comprehension, but it's available to the lambda because the lambda is in its scope.
    2. Yes, lambdas are closures. Variable binding might not always work the way you want it to, but they're closures. You shouldn't rely on them heavily, though.
    3. You'd just want to loop over xrange(10). You could do this with lambdas (see the other answer), but you wouldn't want to. Lambdas should be used pretty sparingly.

    The reason that the lambda behaves this way is because for each loop i is rebound. Since i isn't local to the lambda, it changes too, and the last value it holds is 9. So all you're doing is 0 + 9 10 times.

提交回复
热议问题