Re: Modifying every alternate element of a sequence
- From: "John Hicken" <john.hicken@xxxxxxxxx>
- Date: 28 Nov 2006 03:21:45 -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.
--
Suresh
I would tend to do this as a list comprehension. In python 2.5 you can
do this:
wanted = [(v if i % 2 == 0 else -v) for (i,v) in enumerate(input)]
(a if b else c) is new to Python 2.5. You don't always need the
brackets, but I think it makes things clearer. See
(http://docs.python.org/whatsnew/pep-308.html) for more details on this
feature.
With earlier versions, you could do
wanted = [v - 2*(i % 2) for (i,v) in enumerate(input)]
That looks less clear to me than your version, though.
John Hicken
.
- 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: SAX2 Download
- Previous by thread: Re: Modifying every alternate element of a sequence
- Next by thread: Re: Modifying every alternate element of a sequence
- Index(es):
Relevant Pages
|