Re: Modifying every alternate element of a sequence



On Tue, 28 Nov 2006 02:38:09 -0800, jm.suresh@xxxxxxxxxxxxxxxxx wrote:

I have a list of numbers and I want to build another list with every
second element multiplied by -1.

input = [1,2,3,4,5,6]
wanted = [1,-2,3,-4,5,-6]

I can implement it like this:

input = range(3,12)
wanted = []
for (i,v) in enumerate(input):
if i%2 == 0:
wanted.append(v)
else:
wanted.append(-v)

But is there any other better way to do this.


Lots of ways.

Other people have given you some solutions. In my opinion, this is
the simplest method of all, if you want to modify input in place:

for i in range(1, len(input), 2):
input[where] = -input[where]


Here's another method that only works if there are an even number of items:

A = input[0::2] # extended slicing
B = input[1::2]
B = [-x for x in B]
tmp = zip(A, B) # but watch out for odd number of items!
result = []
for t in tmp:
result.extend(t)


Here's a third method:

factors = [(-1)**i for i in range(len(input))]
output = map(operator.mul, input, factors)


As for which is best, I leave that to you to decide.


--
Steven.

.



Relevant Pages

  • Re: zero byte tmp file on the desktop
    ... files starting with FR and then various numbers with an extension ... of .tmp and has no idea what generated these files, ... You could try using Sysinternals's Process Explorer utility to watch ...
    (microsoft.public.windowsxp.general)
  • Re: Compiled in D5.1 but fails on D6
    ... doesn't seem right somehow, neither Smalltalk nor C*... ... I agree that there's something odd about it. ... tmp:= self baz. ...
    (comp.lang.smalltalk.dolphin)