反转列表中的元组

时间:2013-04-23 06:59:23

标签: python list

我有这个清单:

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

我怎样才能把它变成这个:

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

我只想反转元组中的内容

5 个答案:

答案 0 :(得分: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]使用slice syntax来反转它前面的容器。请注意,这仅适用于支持切片语法的容器。

答案 1 :(得分:7)

如果你知道元组的长度只有2:

[(b, a) for a, b in lst]

答案 2 :(得分:0)

使用步长为-1的切片

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

答案 3 :(得分:0)

>>> L =  [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [(i[1], i[0]) for i in L]
对于两个元素,

可能只是

答案 4 :(得分: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