Efficient way to rotate a list in python

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

    Numpy can do this using the roll command:

    >>> import numpy
    >>> a=numpy.arange(1,10) #Generate some data
    >>> numpy.roll(a,1)
    array([9, 1, 2, 3, 4, 5, 6, 7, 8])
    >>> numpy.roll(a,-1)
    array([2, 3, 4, 5, 6, 7, 8, 9, 1])
    >>> numpy.roll(a,5)
    array([5, 6, 7, 8, 9, 1, 2, 3, 4])
    >>> numpy.roll(a,9)
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    

提交回复
热议问题