在python中旋转列表的有效方法

发布于 2021-02-02 23:19:42

在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]

有没有更好的办法?

关注者
0
被浏览
103
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    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]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看