Efficient way to rotate a list in python

后端 未结 26 1206
一生所求
一生所求 2020-11-22 03:14

What is the most efficient way to rotate a list in python? Right now I have something like this:

>>> def rotate(l, n):
...     return l[n:] + l[:n]         


        
26条回答
  •  青春惊慌失措
    2020-11-22 03:58

    A collections.deque is optimized for pulling and pushing on both ends. They even have a dedicated rotate() method.

    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]
    

提交回复
热议问题