2013-04-23 45 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