Efficient way to rotate a list in python

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

    For a list X = ['a', 'b', 'c', 'd', 'e', 'f'] and a desired shift value of shift less than list length, we can define the function list_shift() as below

    def list_shift(my_list, shift):
        assert shift < len(my_list)
        return my_list[shift:] + my_list[:shift]
    

    Examples,

    list_shift(X,1) returns ['b', 'c', 'd', 'e', 'f', 'a'] list_shift(X,3) returns ['d', 'e', 'f', 'a', 'b', 'c']

提交回复
热议问题