Efficient way to rotate a list in python

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

    Following function copies sent list to a templist, so that pop function does not affect the original list:

    def shift(lst, n, toreverse=False):
        templist = []
        for i in lst: templist.append(i)
        if toreverse:
            for i in range(n):  templist = [templist.pop()]+templist
        else:
            for i in range(n):  templist = templist+[templist.pop(0)]
        return templist
    

    Testing:

    lst = [1,2,3,4,5]
    print("lst=", lst)
    print("shift by 1:", shift(lst,1))
    print("lst=", lst)
    print("shift by 7:", shift(lst,7))
    print("lst=", lst)
    print("shift by 1 reverse:", shift(lst,1, True))
    print("lst=", lst)
    print("shift by 7 reverse:", shift(lst,7, True))
    print("lst=", lst)
    

    Output:

    lst= [1, 2, 3, 4, 5]
    shift by 1: [2, 3, 4, 5, 1]
    lst= [1, 2, 3, 4, 5]
    shift by 7: [3, 4, 5, 1, 2]
    lst= [1, 2, 3, 4, 5]
    shift by 1 reverse: [5, 1, 2, 3, 4]
    lst= [1, 2, 3, 4, 5]
    shift by 7 reverse: [4, 5, 1, 2, 3]
    lst= [1, 2, 3, 4, 5]
    

提交回复
热议问题