First time here? Check out the FAQ!

Ask Your Question
0

Swap coordinates of list elements

asked 13 years ago

sagefan gravatar image

updated 13 years ago

Suppose I have list like

L = [(2,3), (4,5), (6,7)]

What's the easiest way to transform it to this list:

L'=[(3,2),(5,4),(7,5)]

i.e. swap the coordinates in each entry.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 13 years ago

DSM gravatar image

There are several ways to do this. Which one I'd use would depend more upon the context, because I'd probably write the one which generalized most naturally.

First, explicitly (useful if we're sticking with 2D or if I might be interested in other transformations):

>>> L = [(2,3), (4,5), (6,7)]
>>> M = [(y,x) for x,y in L]
>>> M
[(3, 2), (5, 4), (7, 6)]

or maybe using slice notation (seq[start:stop:step]):

>>> M = [v[::-1] for v in L]
>>> M
[(3, 2), (5, 4), (7, 6)]

Or, using words instead:

>>> M = [tuple(reversed(v)) for v in L]
>>> M
[(3, 2), (5, 4), (7, 6)]
>>> M = list(tuple(reversed(v)) for v in L)
>>> M
[(3, 2), (5, 4), (7, 6)]

And if the objects are really vectors, then maybe I'd use a rotation matrix. All depends, but I have to admit if there were only two things to swap I'd reach for the first method.

Preview: (hide)
link

Comments

Umm, wouldn't you try to use the *fastest* one, all else being equal? Using `L = [(randint(0,10),randint(0,10)) for i in range(10000)]`, the first one wins hands down. A little (numerical, not # of ops) analysis shows that the first two options are slightly superlinear in the length of the list while the last is nearly exactly O(n^2). Anyway, go with the first one if you really only have pairs!

kcrisman gravatar imagekcrisman ( 13 years ago )

@kcrisman: well, sometimes I might want to use the most general one, all else being equal. Not everything's sliceable. (slicable?) I don't see O(n^2), though-- which list length are you talking about, L or v? Maybe I typed it wrong.

DSM gravatar imageDSM ( 13 years ago )

Sorry, I was referring to L. Adding a zero multiplied the timing by about 100 each time, it was quite impressive.

kcrisman gravatar imagekcrisman ( 13 years ago )

I really don't seem to be able to reproduce this. timeit shows almost exactly linear growth for me. Could you double-check that? (Could be a memory reallocation thing? Hard to see where the nonlinearity would come from otherwise.)

DSM gravatar imageDSM ( 13 years ago )

Strange - I could have sworn - but I get linear now too. Huh. That doesn't change the point that the first option still is the fastest :)

kcrisman gravatar imagekcrisman ( 13 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 13 years ago

Seen: 908 times

Last updated: Feb 08 '12