首先,lambda 是一个匿名函数,调用的时候需要加上(),参数传递的时候尤其容易出问题,那么我们上一段易错的代表性代码。
squares = []
for x in range(5):
squares.append(lambda: x**2)
print(squares[1]())
原因:
This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4, so all the functions now return 4**2, i.e. 16.
那如何实现我们想要的结果呢?
为了避免这种情况,需要将值保存在lambda的局部变量中,这样它们就不会依赖于全局x的值
squares = []
for x in range(5):
squares.append(lambda n = x: n ** 2)
print("lambda n =x: n ** 2",squares[1]())
Here, n=x creates a new variable n local to the lambda and computed when the lambda is defined so that it has the same value that x had at that point in the loop. This means that the value of n will be 0 in the first lambda, 1 in the second, 2 in the third, and so on.