Python数组操作

Jaa*_*nus 1 python arrays

我有阵列 [1,2,1,2,3,4,3,4,1,2]

我想循环x次,每次向前移动每个元素1位置的数组:

所以下一个循环将是:

2.[2,1,2,3,4,3,4,1,2,1]

3. [1,2,3,4,3,4,1,2,1,2]

等等....

我怎样才能像这样操纵数组呢?

编辑:

我的想法,但也许一些更好的技巧:

只需使用while循环遍历数组并使用for循环创建新数组.

for i in range(11)
    array[i] = array[i-1]
Run Code Online (Sandbox Code Playgroud)

等等.伪代码

Lew*_*ond 5

使用List数据结构不是一种有效的方法.甲队列将更为合适.在任何情况下:

使用队列

正如我所建议的那样,使用Queue(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])
Run Code Online (Sandbox Code Playgroud)

保持清单

>>> 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]
Run Code Online (Sandbox Code Playgroud)

或者(比前一个更快):

>>> 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]
Run Code Online (Sandbox Code Playgroud)

在这里你可以改变你想要迭代的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
Run Code Online (Sandbox Code Playgroud)

切片

>>> 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
Run Code Online (Sandbox Code Playgroud)

队列

>>> 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
Run Code Online (Sandbox Code Playgroud)

通过一点优化,基本上删除__getattr__调用for 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
Run Code Online (Sandbox Code Playgroud)

队列

>>> 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
Run Code Online (Sandbox Code Playgroud)