我有这个清单:
[(3, 28), (25, 126), (25, 127), (26, 59)]
我怎样才能把它变成这样:
[(28, 3), (126, 25), (127, 25), (59, 26)]
我只想反转元组中的内容
>>> lst = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [i[::-1] for i in lst]
[(28, 3), (126, 25), (127, 25), (59, 26)]
[::-1]
使用切片语法来反转它之前的容器。请注意,这仅适用于支持切片语法的容器。
如果您知道元组的长度仅为 2:
[(b, a) for a, b in lst]
使用步长为 -1 的切片
>>> [x[::-1] for x in [(3, 28), (25, 126), (25, 127), (26, 59)]]
[(28, 3), (126, 25), (127, 25), (59, 26)]
>>> L = [(3, 28), (25, 126), (25, 127), (26, 59)]
>>> [(i[1], i[0]) for i in L]
可能仅对两个元素有用。
有趣的选择
>>> 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