lambda in list comprehension acting funny
Rotwang
sg552 at hotmail.co.uk
Thu Jul 12 19:23:10 CEST 2012
On 12/07/2012 04:59, Steven D'Aprano wrote:
> On Wed, 11 Jul 2012 08:41:57 +0200, Daniel Fetchinson wrote:
>
>> funcs = [ lambda x: x**i for i in range( 5 ) ]
>
> Here's another solution:
>
> from functools import partial
> funcs = [partial(lambda i, x: x**i, i) for i in range(5)]
>
>
> Notice that the arguments i and x are defined in the opposite order.
> That's because partial only applies positional arguments from the left.
> If there was a "right partial" that applies from the right, we could use
> the built-in instead:
>
> funcs = [rpartial(pow, i) for i in range(5)]
I don't think anyone has suggested this yet:
funcs = [(lambda i: lambda x: x**i)(i) for i in range(5)]
It's a bit more opaque than other solutions, but it fits in one line and
avoids defining functions with an implicit second argument, if that's
desirable for some reason.
--
I have made a thing that superficially resembles music:
http://soundcloud.com/eroneity/we-berated-our-own-crapiness
More information about the Python-list
mailing list