In [310]: lambdas = [lambda x: x + i for i in range(10)] In [311]: [f(10) for f in lambdas] Out[311]: [19, 19, 19, 19, 19, 19, 19, 19, 19, 19]
Obviously, we have a scoping issue. It might be because the coffee has not yet kicked in, but I'd like to find a way to get the intuitively correct result, which would be
Out[311]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
ie, the value of i in the lambda function should be the value at the time the function is defined, not the value
Any thoughts? The original problem is about defining columns in a report dynamically. The lambdas are for the data lookup function which is part of the column definition.
Note that it is not necessary for the functions to be defined in a comprehension, this was just the easiest way to express the problem. For that matter, lambdas are not strictly needed, I could be perfectly happy with a solution in terms of defs and loops.

New Topic/Question
Reply


MultiQuote



|