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
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.
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
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
578 Understanding How to Configure Google API Key
581 PHP ssh2_scp_send fails to send files as intended
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.