使用 List 数据结构不是执行此操作的有效方法。队列会更合适。任何状况之下:
使用队列
正如我所建议的,使用队列(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('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__ 对 append、pop 和 rotate 的调用:
弹出追加
>>> 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