2013-04-23 57 views
1

我有這樣的名單:扭轉元組列表中的

[(3, 28), (25, 126), (25, 127), (26, 59)]

我怎樣才能把它變成這樣:

[(28, 3), (126, 25), (127, 25), (59, 26)]

我只是想扭轉什麼是在元組

+3

你要嘗試寫任何項目自己?或者你只是要有StackOverflow寫[每](http://stackoverflow.com/questions/16152957/separating-a-list-into-two-lists)[piece](http://stackoverflow.com/questions/16162525/list-of-strings-into-a-list-of-in-ints)? – 2013-04-23 07:01:37

回答

7
>>> lst = [(3, 28), (25, 126), (25, 127), (26, 59)] 
>>> [i[::-1] for i in lst] 
[(28, 3), (126, 25), (127, 25), (59, 26)] 

[::-1]使用th e slice syntax將在其之前的容器翻轉。注意,這隻適用於支持slice語法的容器。

0

使用切片爲-1

>>> [x[::-1] for x in [(3, 28), (25, 126), (25, 127), (26, 59)]] 
[(28, 3), (126, 25), (127, 25), (59, 26)] 
7

一步如果你知道元組將只長2:

[(b, a) for a, b in lst] 
0
>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)] 
>>> [(i[1], i[0]) for i in L] 

可能有用的只是兩元件。

+1

比'[(b,a)for a,b in L]醜得多' – wim 2013-04-23 07:16:58

0

搞怪另類

>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)] 
>>> zip(*zip(*L)[::-1]) 
[(28, 3), (126, 25), (127, 25), (59, 26)] 

或某些邪惡過早的優化:

>>> from operator import itemgetter 
>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)] 
>>> map(itemgetter(slice(None, None, -1)), L) 
[(28, 3), (126, 25), (127, 25), (59, 26)] 

時序:

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]" "[i[::-1] for i in L]" 
1000000 loops, best of 3: 1.21 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]" "zip(*zip(*L)[::-1])" 
100000 loops, best of 3: 2.26 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]; from operator import itemgetter;" "map(itemgetter(slice(None, None, -1)), L)"  
100000 loops, best of 3: 1.69 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100" "[i[::-1] for i in L]" 
10000 loops, best of 3: 87.4 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100" "zip(*zip(*L)[::-1])" 
10000 loops, best of 3: 67.1 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100;from operator import itemgetter;" "map(itemgetter(slice(None, None, -1)), 
L)" 
10000 loops, best of 3: 66.1 usec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100000" "[i[::-1] for i in L]" 
10 loops, best of 3: 108 msec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100000" "zip(*zip(*L)[::-1])" 
10 loops, best of 3: 109 msec per loop 

python -m timeit -s "L = [(3, 28), (25, 126), (25, 127), (26, 59) 
]*100000;from operator import itemgetter;" "map(itemgetter(slice(None, None, -1) 
), L)" 
10 loops, best of 3: 82.9 msec per loop 
+1

我發現Toomuchgolfitis! – Volatility 2013-04-23 07:11:01

+0

@Volatility足夠有趣它甚至不比列表比較短。然而,它會產生一些有趣的時機...我會盡快發佈它們 – jamylak 2013-04-23 07:11:39

+0

實際上這並不是那麼有趣,但我發佈了一些時機,顯示了最快的方式來做到這一點。雙'zip'可以快速減少巨大的數據 – jamylak 2013-04-23 07:32:35