Efficient way to rotate a list in python

后端 未结 26 1183
一生所求
一生所求 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:51

    I take this cost model as a reference:

    http://scripts.mit.edu/~6.006/fall07/wiki/index.php?title=Python_Cost_Model

    Your method of slicing the list and concatenating two sub-lists are linear-time operations. I would suggest using pop, which is a constant-time operation, e.g.:

    def shift(list, n):
        for i in range(n)
            temp = list.pop()
            list.insert(0, temp)
    

提交回复
热议问题