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

前端 未结 12 1718
天涯浪人
天涯浪人 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: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.

提交回复
热议问题