Re: Modifying every alternate element of a sequence
- From: Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 28 Nov 2006 23:24:12 +1100
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.
.
- References:
- Modifying every alternate element of a sequence
- From: jm.suresh@xxxxxxxxxxxxxxxxx
- Modifying every alternate element of a sequence
- Prev by Date: Re: Modifying every alternate element of a sequence
- Next by Date: Re: Python script and C++
- Previous by thread: Re: Modifying every alternate element of a sequence
- Next by thread: How to secure your network
- Index(es):
Relevant Pages
|