[SciPy-User] List of functions with different arguments
Fri Mar 1 13:53:39 CST 2013
On Fri, Mar 1, 2013 at 2:24 PM, Per Nielsen <firstname.lastname@example.org> wrote:
> Hi all
> I apologize if this is too off topic, but I figured it was common in
> scientific computing.
> I am trying to make a list of copies of the same function, but with
> different extra input arguments. However, I am having problems getting the
> wanted output. I thought it was a problem with the way I refered to the
> function, but I tried a deepcopy and also the functions seem to have
> different ids.
> Here is my output from the attached script:
> [3, 3, 3]
> [4549677376, 4549677496, 4549677616]
> [3, 3, 3]
> [4549677736, 4549677856, 4549677976]
> wanted/expected output: [1, 2, 3]
> Any help would be greatly appreciated :)
The problem is this:
fct_list = [lambda x: fct(x, aa) for aa in range(1, 4)]
does not do what you want it to. The use of `aa` in the lambda expression
is not replaced by the values of `aa` in the list comprehension. Instead,
your lambdas will use whatever value the name 'aa' has when they are
called. In this case, after the list comprehension is done, `aa` is 3, so
they always get a=3. In fact, if immediately after you define `fct_list`
you do `del aa`, you'll get an error when you try to call fct_list(1).
One alternative is to import `partial` from `functools`:
from functools import partial
fct_list = [partial(fct, a=aa) for aa in range(1, 4)]
> SciPy-User mailing list
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the SciPy-User