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

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

提交回复
热议问题