Shift list elements to the right and shift list element at the end to the beginning

前端 未结 12 1517
天涯浪人
天涯浪人 2021-02-08 08:43

I want to rotate elements in a list, e.g. - shift the list elements to the right so [\'a\',\'b\',\'c\',\'d\'] would become [\'d\',\'a\',\'b\',\'c\'], o

相关标签:
12条回答
  • 2021-02-08 09:08

    You can use negative indices together with list concatenation:

    def shift(seq, n=0):
        a = n % len(seq)
        return seq[-a:] + seq[:-a]
    
    0 讨论(0)
  • 2021-02-08 09:08

    The question seems to imply to me that the list itself should be modified rather than a new list created. A simple in place algorithm is therefore:

    lst = [1, 2, 3, 4, 5]
    
    e1 = lst[-1]
    for i, e2 in enumerate(lst):
        lst[i], e1 = e1, e2
    
    print(lst)
    

    Giving:

    [5, 1, 2, 3, 4]
    
    0 讨论(0)
  • 2021-02-08 09:09

    If you are allergic to slice notation: a.insert(0,a.pop())

    Usage:

    In [15]: z=[1,2,3]
    
    In [16]: z.insert(0,z.pop())
    
    In [17]: z
    Out[17]: [3, 1, 2]
    
    In [18]: z.insert(0,z.pop())
    
    In [19]: z
    Out[19]: [2, 3, 1]
    
    0 讨论(0)
  • 2021-02-08 09:11

    This could be done simply by using list method: insert,

    values = [2, 3, 5, 7, 11, 13]
    
    def shift(list):
        new_list = []
    
        for i in list:
            new_list.insert(len(new_list)-1, i)
    
        return new_list
    

    print(shift(values))

    Output is:

    [3, 5, 7, 11, 13, 2]
    
    0 讨论(0)
  • 2021-02-08 09:13

    You can just slice the last element off the list, then add it to the beginning of a new list:

    aList = [aList[-1]] + aList[:-1]
    

    Here is the result:

    >>> aList = [1,2,3]
    >>> aList = [aList[-1]] + aList[:-1]
    >>> aList
    [3, 1, 2]
    
    0 讨论(0)
  • 2021-02-08 09:13

    Simple use of slice syntax:

    def shift(seq):
        return [seq[-1]] + seq[:-1]
    
    assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
    

    Generalized version with changeable shift:

    def shift(seq, shift=1):
        return seq[-shift:] + seq[:-shift]
    
    assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
    assert shift([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
    
    0 讨论(0)
提交回复
热议问题