Help with map python 2

flebber flebber.crue at gmail.com
Mon Jan 5 06:33:46 EST 2015


> You could do what mathematicians do when they deal with alternating
> signs: they raise -1 to the power of the index to get an appropriate
> multiplier.
> 
>    >>> [ n * (-1) ** n for n in range(10) ]
>    [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]
>    >>> 
> 
> Or you could do here what you attempt to do with map below. See below.
> 

> 
> You are trying to use a binary expression. There are no binary
> expressions. Add an else branch to make it ternary:
> 
>    lambda x : x if x % 2 == 0 else -x
> 
> But never mind the number of branches, the serious point is that you
> didn't specify a value for when the condition is not true. It doesn't
> make sense without that.
> 
> There's nothing wrong with a list comprehension, or the corresponding
> generator expression if you want a generator. It's fine. Map's fine.

Thanks Jussi  I really like the multiplier solution.



More information about the Python-list mailing list