I want to create a list of lambda objects from a list of constants in Python; for instance:
listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
This will create a list of lambda objects, however, when I run them:
for f in listOfLambdas:
print f(),
I would expect that it would print
1 4 9 16 25
Instead, it prints:
25 25 25 25 25
It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.
EDIT: a bit more of trying things and such came up with this:
listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
Prints the expected squares from 1 to 25, but then using the earlier print statement:
for f in listOfLambdas:
print f(),
still gives me all 25
s. How did the existing lambda objects change between those two print calls?
Related question: Why results of map() and list comprehension are different?
question from:
https://stackoverflow.com/questions/66061935/how-to-generate-a-list-of-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…