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

前端 未结 12 1516
天涯浪人
天涯浪人 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 08:53

    Use a function assuming n is the shift that is less than the length of list l like so:

    shift = lambda l, n: l[-n:] + l[:-n] # i.e. shift([1, 2, 3, 4], 3)
    
    0 讨论(0)
  • 2021-02-08 08:54

    If you are trying to shift the elements, use collections.deque rotate method:

    #! /usr/bin/python3
    
    from collections import deque
    a = deque([1, 2, 3, 4])
    a.rotate()
    print(a)
    

    Result:

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

    You can use this:

    li=li[-1:]+li[:-1]
    
    0 讨论(0)
  • 2021-02-08 08:55

    you can use roll function from numpy.

    >>> import numpy as np
    >>> q = [1, 2, 3, 4, 5]
    >>> np.roll(q, 2)
    array([4, 5, 1, 2, 3])
    

    Hope it helps!

    0 讨论(0)
  • 2021-02-08 08:59

    If you actually want to shift the elements, you can use modulo to cycle the list and reassign the elements to their shifted positions:

    def shift(lst, shft=0):
        ln = len(lst)
        for i, ele in enumerate(lst[:]):
            lst[(i + shft) % ln] = ele
        return lst
    
    In [3]: shift( ['a','b','c','d'] , 1)
    Out[3]: ['d', 'a', 'b', 'c']
    
    In [4]: shift( ['a','b','c','d'] , 2)
    Out[4]: ['c', 'd', 'a', 'b']
    
    In [5]: shift( ['a','b','c','d'] , 3)
    Out[5]: ['b', 'c', 'd', 'a']
    

    If you only want a single shift just shift the last element to the front extending the list:

    def shift(lst):
        lst[0:1] = [lst.pop(),lst[0]]
        return lst
    

    Both of which change the original list.

    0 讨论(0)
  • 2021-02-08 09:00

    Solution for your query :

    def shift(aList):
        l = list()
        n = len(aList)
        l.append(aList[-1])
        temp = aList[:n-1]
        for i in temp:
            l.append(i)
        return l
    print(shift(aList=[1,2,3]))
    
    0 讨论(0)
提交回复
热议问题