473,322 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Modifying every alternate element of a sequence

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

Nov 28 '06 #1
9 1216

jm*******@no.spam.gmail.com 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

Nov 28 '06 #2
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)
>>input = range(3,12)
[i%2==0 and v or -v for (i,v) in enumerate(input)]
[3, -4, 5, -6, 7, -8, 9, -10, 11]
But is there any other better way to do this.
I'm not sure densely packing it into a list comprehension is
necessarily a *better* way, just a more compact way.

To make more sense of it, you might create a helper function that
does your comparison work:

def inv_if(v, test):
if test:
return v
else:
return -v

[inv_if(v, i%2==0) for (i,v) in enumerate(input)]
Or you could even do something like

def inv_alternating(t):
i, v = t
if i%2==0:
return v
else:
return -v

[inv_alternating(t) for t in enumerate(input)]

Either compacts it for the actual call within a list
comprehension, but it is cleaner to read what's going on.

-tkc

Nov 28 '06 #3

jm*******@no.spam.gmail.com 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.
Use slices:

input[1::2] = [-item for item in input[1::2]]

If you don't want to do it in-place, just make a copy:

wanted = input[:]
wanted[1::2] = [-item for item in wanted[1::2]]

-- Leo

Nov 28 '06 #4
On 2006-11-28, jm*******@no.spam.gmail.com <jm*******@gmail.comwrote:
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.
Wether this is better, I'll leave that for others to decide. But this
is a possibility:

wanted = [ (1 - 2*(i%2)) * item for i, item in enumerate(input)]

--
Antoon Pardon
Nov 28 '06 #5
Wow, I was in fact searching for this syntax in the python tutorial. It
is missing there.
Is there a reference page which documents all possible list
comprehensions.
--
Suresh
Leo Kislov wrote:
jm*******@no.spam.gmail.com 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.

Use slices:

input[1::2] = [-item for item in input[1::2]]

If you don't want to do it in-place, just make a copy:

wanted = input[:]
wanted[1::2] = [-item for item in wanted[1::2]]

-- Leo
Nov 28 '06 #6
jm*******@no.spam.gmail.com wrote:
I have a list of numbers and I want to build another list with every
second element multiplied by -1.
[...]
But is there any other better way to do this.
I think the best way is the one that uses slices, as somebody suggested
in this thread. This is another (worse) way, just for fun:
>>from itertools import cycle
input = [1, 2, 3, 4, 5, 6]
wanted = [x * sign for x, sign in zip(input, cycle([1, -1]))]
wanted
[1, -2, 3, -4, 5, -6]

Cheers,
--
Roberto Bonvallet
Nov 28 '06 #7
On Tue, 28 Nov 2006 02:38:09 -0800, jm*******@no.spam.gmail.com 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.

Nov 28 '06 #8
jm*******@no.spam.gmail.com wrote:
Wow, I was in fact searching for this syntax in the python tutorial. It
is missing there.
Is there a reference page which documents all possible list
comprehensions.
There is actually only two forms of list comprehensions:
http://docs.python.org/ref/lists.html
[blah for x in expr] and [blah for x in expr if cond]

And here is reference page for slicing (note, it's not list
comprehension): http://docs.python.org/ref/slicings.html

-- Leo

Nov 28 '06 #9
Leo Kislov:
input[1::2] = [-item for item in input[1::2]]
If you don't want to do it in-place, just make a copy:
wanted = input[:]
wanted[1::2] = [-item for item in wanted[1::2]]
Very nice solution.
I have tried few versions like:
from itertools import imap, islice
from operator import neg
1) data[1::2] = [-el for el in data[1::2]]
2) data[1::2] = map(neg, data[1::2])
3) data[1::2] = imap(neg, data[1::2])
4) data[1::2] = map(neg, islice(data, 1, None, 2))
5) etc.

With Python 2.5 it seems that the n.2 (map + slicing) is the faster.

Bye,
bearophile

Nov 28 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Steel | last post by:
Hi at all, I have a very long html page with many photo. Therefore the best to print this page is to print the some page as PDF. Therefore I maked a PDF file like my page to print best. I'ld want...
11
by: Jason Heyes | last post by:
Look at my code: void modify_element(BigType &x) { /* not shown */ } BigType modify_element_copy(BigType x) { modify_element(x);
2
by: Kirk Is | last post by:
Hi there. I'm trying to improve a simple javascript based graphics editor for Atari 2600 games (long story) with better use of CSS and Javascript. I'm a little weak on what CSS can and can't...
1
by: jrmsmo | last post by:
Hi there, I have an interesting problem that maybe you pros can suggest how I solve. I'm working with a third party program that serializes an XML document (it was obviously not designed with schema...
2
by: Tarren | last post by:
Hi: The problem I am having is when I validate an xml file to a schema, it is erroring out every element. I think this has something to do with me defining/referencing the namespaces. I have...
4
by: Mike | last post by:
I have a web service being consume by a new client. The WebMethod they are calling is called Process. So in the WSDL I have has 2 elements, Process and ProcessResponse. <s:schema...
1
by: Sean Burns | last post by:
Hello, I am busy creating my first XSD and folloing the examples and tutorials from "everywhere" I came up with an xsd that does the job, but I need a alternate to "sequence" because I do not...
5
by: MightyTater | last post by:
Hey all, I am very new to python, and not usually a programmer. Have mercy, please :) I am comparing road address ranges to find inconsistencies. Some roads are much longer than others and are...
5
by: Alan | last post by:
I was wondering whether it is good programming practice or asking for trouble to modify a vector while iterating through it. That is, I want to do something like the following pseudocode in C++: ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.