在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]
有没有更好的办法?
A collections.deque已针对两端的推拉进行了优化。他们甚至有专门的rotate()方法。
A collections.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]