使用列表數據結構是不是做這個的有效途徑。 A 隊列會更合適。在任何情況下:
使用隊列
正如我建議的,使用隊列(collections.deque):
>>> q = collections.deque([1,2,3,4,5,6,7,8])
>>> for _ in xrange(5):
... q.rotate(-1)
...
>>> q
deque([6, 7, 8, 1, 2, 3, 4, 5])
保持列表
>>> a = [1,2,3,4,5,6,7,8]
>>> for _ in xrange(5):
... a = a[1:] + a[:1]
...
>>> a
[6, 7, 8, 1, 2, 3, 4, 5]
備選地(更快比前一個):
>>> a = [1,2,3,4,5,6,7,8]
>>> for _ in xrange(5):
... a.append(a.pop(0))
...
>>> a
[6, 7, 8, 1, 2, 3, 4, 5]
在這裏你可以改變xrange的任何你想要迭代。
Timeit分析:
彈出追加
>>> timeit.timeit('a.append(a.pop(0))', setup='a = [0,1,2,3,4,5,6,7,8,9]', number=1000000)
0.24548697471618652
>>> timeit.timeit('a.append(a.pop(0))', setup='a = [0,1,2,3,4,5,6,7,8,9]', number=100000000)
23.65538215637207
切片
>>> timeit.timeit('a=a[1:] + a[:1]', setup='a = [0,1,2,3,4,5,6,7,8,9]', number=1000000)
0.36037278175354004
>>> timeit.timeit('a=a[1:] + a[:1]', setup='a = [0,1,2,3,4,5,6,7,8,9]', number=100000000)
35.06173801422119
隊列
>>> timeit.timeit('q.rotate(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8])', number=1000000)
0.16829514503479004
>>> timeit.timeit('q.rotate(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8])', number=100000000)
16.012277841567993
隨着一點點的優化,基本上消除了__getattr__呼籲追加,流行和旋轉:
彈出式追加
>>> timeit.timeit('aa(ap(0))', setup='a = [0,1,2,3,4,5,6,7,8,9]; aa=a.append; ap=a.pop', number=1000000)
0.15255093574523926
>>> timeit.timeit('aa(ap(0))', setup='a = [0,1,2,3,4,5,6,7,8,9]; aa=a.append; ap=a.pop', number=100000000)
14.50795292854309
隊列
>>> timeit.timeit('r(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8]); r=q.rotate', number=1000000)
0.13374090194702148
>>> timeit.timeit('r(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8]); r=q.rotate', number=100000000)
11.435136079788208
你試過什麼了嗎? – dm03514
聽起來像HW?你必須嘗試學習! :) –
你試過的任何代碼?? –