Efficient way to rotate a list in python

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

    It depends on what you want to have happen when you do this:

    >>> shift([1,2,3], 14)
    

    You might want to change your:

    def shift(seq, n):
        return seq[n:]+seq[:n]
    

    to:

    def shift(seq, n):
        n = n % len(seq)
        return seq[n:] + seq[:n]
    

提交回复
热议问题