Unexpected behavior when applying a list of lambda functions to another list

I am trying to create a list of functions that I then apply to a list of numbers. I do this by iterating through a series of numbers and defining a lambdas function with each number from the for loop. Then the second loop is used to apply each function to the same list of 10 numbers.

The problem is that my list of lambdas seems to be accepting the final value of the for loop.

fx_lst = []
for k in range(1,3,1):
    func = lambda x_: k * x_
    fx_lst.append(func)
xlst = range(1,10,1)

for fx in fx_lst:
    ylst = map(lambda xin_: fx(xin_), xlst)
    print i, ylst

ylst prints: [2,4,6 ... 18] [2,4,6 ... 18]

Obviously, I don't understand something about how lambdas stores variable information.

+4
source share
2 answers

, , k, , . k , lambdas .

, , lambda currying:

In [129]: fx_lst = []
     ...: for k in range(1,3,1):
     ...:     func = (lambda k=k: lambda x_: k * x_)(k)
     ...:     fx_lst.append(func)
     ...:     

In [130]: fx_lst[0](3)
Out[130]: 3

In [131]: fx_lst[1](3)
Out[131]: 6

(lambda k=k: lambda x_: k * x_)(k) , , , . k=k, .

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8, 10, 12, 14, 16, 18]

functools.partial , .

+3

, :

def apply_filters(filters, iterator):
    from functools import reduce
    return list(reduce(lambda s, f: filter(f, s), filters, iterator))

:

my_filters = [lambda x: x % 2 == 0, lambda x: x % 5 == 0]
result = apply_filters(my_filters, range(1, 100))
print(result)
# [10, 20, 30, 40, 50, 60, 70, 80, 90]
+1

Source: https://habr.com/ru/post/1685001/


All Articles