Help with map python 2

Jussi Piitulainen jpiitula at ling.helsinki.fi
Sun Jan 4 13:08:58 CET 2015


flebber writes:

> In repsonse to this question: Write a program that prints the first
> 100 members of the sequence 2, -3, 4, -5, 6, -7, 8.
> 
> This is my solution it works but ugly.

Seems respectable to me, except that you are taking fewer than 100
elements. But I'd prefer the expressions that you are looking for.

> series = range(2,100)
> # answer = [(x,(y* -1)) for x, y in series[::2]]

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.

> # print(answer)
> answer = []
> for item in series:
>     if item % 2 != 0:
>         answer.append(item * -1)
>     else:
>         answer.append(item)
> 
> print(answer)
> 
> I know I should be better off doing this with map but cannot get it
> to work. I understand also that map returns a generator so this
> solution should only working in python2(correct me please if I am
> wrong).
> 
> In [6]: map?
> Type:       builtin_function_or_method
> String Form:<built-in function map>
> Namespace:  Python builtin
> Docstring:
> map(function, sequence[, sequence, ...]) -> list
> 
> Just getting something wrong
> list(map((lambda x: x * -1 if (x%2 != 0)), series))

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.



More information about the Python-list mailing list