Efficient way to rotate a list in python

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

    If you just want to iterate over these sets of elements rather than construct a separate data structure, consider using iterators to construct a generator expression:

    def shift(l,n):
        return itertools.islice(itertools.cycle(l),n,n+len(l))
    
    >>> list(shift([1,2,3],1))
    [2, 3, 1]
    

提交回复
热议问题