A Faster Way...

Bill Mill bill.mill at gmail.com
Tue May 10 13:07:23 EDT 2005


On 5/10/05, andrea.gavana at agip.it <andrea.gavana at agip.it> wrote:
> Hello NG,
> 
>       it is probably a beginner question, but I didn't solve it without
> for-loops, and I am unable to determine if there is a faster way (probably
> using some built-in function) to do this task. I have to speed up a
> wxPython code that uses a lot of string concatenation (and uses these
> strings to build some Fancy StaticText Controls). I found a way, but I need
> a little bit of help from you, NG.
> 
> If I simplify the problem, suppose I have 2 lists like:
> 
> a = range(10)
> b = range(20,30)
> 
> What I would like to have, is a "union" of the 2 list in a single tuple. In
> other words (Python words...):

well a "union" can be obtained with:

>>> z = range(10) + range(20, 30)
>>> z
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

> 
> c = (0, 20, 1, 21, 2, 22, 3, 23, 4, 24, 5, 25, .....

Alternating the items can be done by:

>>> [z[((i%2)*(len(z/2)))+i/2] for i in range(len(z))]
[0, 20, 1, 21, 2, 22, 3, 23, 4, 24, 5, 25, 6, 26, 7, 27, 8, 28, 9, 29]

Or in a slightly different format:

>>> zip(range(10), range(20, 30))
[(0, 20), (1, 21), (2, 22), (3, 23), (4, 24), (5, 25), (6, 26), (7, 27), (8, 28)
, (9, 29)]

> Sorry if it seems an homework assignment.

It'd be one heck of a short homework assignment. I hope you've read
the python tutorial at http://docs.python.org/tut/tut.html ; it'll
help you a lot to go through it a couple times.

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list