在Python列表中交换元素的最快方法

有什么更快的方法来交换Python中的两个列表元素

L[a], L[b] = L[b], L[a] 

或者我会不得不求助于Cython或编织或类似的?

看起来像Python编译器优化了这个结构的临时元组:

码:

 import dis def swap1(): a=5 b=4 a, b = b, a def swap2(): a=5 b=4 c = a a = b b = c print 'swap1():' dis.dis(swap1) print 'swap2():' dis.dis(swap2) 

输出:

 swap1(): 6 0 LOAD_CONST 1 (5) 3 STORE_FAST 0 (a) 7 6 LOAD_CONST 2 (4) 9 STORE_FAST 1 (b) 8 12 LOAD_FAST 1 (b) 15 LOAD_FAST 0 (a) 18 ROT_TWO 19 STORE_FAST 0 (a) 22 STORE_FAST 1 (b) 25 LOAD_CONST 0 (None) 28 RETURN_VALUE swap2(): 11 0 LOAD_CONST 1 (5) 3 STORE_FAST 0 (a) 12 6 LOAD_CONST 2 (4) 9 STORE_FAST 1 (b) 13 12 LOAD_FAST 0 (a) 15 STORE_FAST 2 (c) 14 18 LOAD_FAST 1 (b) 21 STORE_FAST 0 (a) 15 24 LOAD_FAST 2 (c) 27 STORE_FAST 1 (b) 30 LOAD_CONST 0 (None) 33 RETURN_VALUE 

两个负载,一个ROT_TWO和两个保存,而不是三个负载和三个保存。 你不可能find更快的机制。

如果您可以发布代表性代码示例,我们可以更好地对您的选项进行基准testing。 FWIW,对于下面的哑巴基准,我得到大约3倍加速与皮肤和10倍加速与PyPy 。

 from time import time def swap(L): for i in xrange(1000000): for b, a in enumerate(L): L[a], L[b] = L[b], L[a] def main(): start = time() L = list(reversed(range(100))) swap(L[:]) print time() - start return L if __name__ == "__main__": print len(main()) # for shedskin: # shedskin -b -r -e listswap.py && make # python -c "import listswap; print len(listswap.main())" 

我发现这个方法是交换两个数字的最快方法:

 mylist = [11,23,5,8,13,17]; first_el = mylist.pop(0) last_el = mylist.pop(-1) mylist.insert(0, last_el) mylist.append(first_el)