在python中旋转列表最有效的方法是什么? 现在我有这样的东西:
>>> def rotate(l, n):
... return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]
有没有更好的办法?
在python中旋转列表最有效的方法是什么? 现在我有这样的东西:
>>> def rotate(l, n):
... return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]
有没有更好的办法?
当前回答
我一直在寻找解决这个问题的方法。这就解决了O(k)的问题。
def solution(self, list, k):
r=len(list)-1
i = 0
while i<k:
temp = list[0]
list[0:r] = list[1:r+1]
list[r] = temp
i+=1
return list
其他回答
deque对两端的拉和推进行了优化。它们甚至有一个专用的rotate()方法。
from collections import deque
items = deque([1, 2])
items.append(3) # deque == [1, 2, 3]
items.rotate(1) # The deque is now: [3, 1, 2]
items.rotate(-1) # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]
如果只使用pop(0)呢?
list.pop([我]) 删除列表中给定位置的项,并返回它。如果 如果没有指定索引,a.pop()将删除并返回中的最后一项 列表中。(方法签名中i周围的方括号 表示参数是可选的,而不是您应该键入square 括号在那个位置。你会经常在 Python库参考。)
我能想到的最简单的方法:
a.append(a.pop(0))
我想你想要的是这个:
a.insert(0, x)
如果效率是你的目标,(周期?内存?),您最好查看数组模块:http://docs.python.org/library/array.html
数组没有列表的开销。
就纯粹的列表而言,你所拥有的就是你所希望做的。