a method of storing lambda functions in a dictionary using a for statement

Asked 2 years ago, Updated 2 years ago, 113 views


because you want to keep multiple functions in dictionary format that have changed the definition little by little. I thought of the following python code.

 funcs={}
for i in range (5):
    new_key='f'+str(i+1)
    funcs [new_key] = lambdax —Stores quadratic functions from x**i#0 order functions

However, if you give arguments to each function, they all return the same value (the value of the last function stored)

for fin funcs.values():
    print(f(5))

Results:

625
625
625
625
625

I would like to return this (1,5,25,125,625).
Could you tell me what to do?

By the way, if you put it one by one without using the for statement, the value was returned correctly.
Also, the id of each function stored by the code above was separate.

for fin funcs.values():
    print(id(f))

Results:

4503380040
4503310120
4503309984
4503309848
4503309168

Thank you for your cooperation.

python lambda

2022-09-30 15:45

2 Answers

funcs [new_key] = lambdax —Stores quadratic functions from x**i#0 order functions

In this line, the i that the lambda function sees is the i itself of the variable, not the value of its contents.The same i is used around in the for statement, so if i is changed, the lambda function will naturally get the latest value when it refers to i later.

Here's an example of a solution:

 funcs [new_key]=(lambdaj:lambdax:x**j)(i)

This takes advantage of the valid range of the lambda function argument only in that lambda function. lambda j:lambda x:x**j is the lambda function that returns the lambda function, but this line is the only valid range for j.


2022-09-30 15:45

This is a separate answer from the original StackOverflow question Python lambda's binding to local values.

The default argument for lambda expressions allows you to bind some values (here i) to values at the time of function object construction using lambda expressions.

funcs [new_key] = lambdax, i=i:x**i


2022-09-30 15:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.