Python:将列表中的元素向右移动,并将列表末尾的元素移动到开头

nes*_*man 6 python

我想在列表中旋转元素,例如 - 将列表元素向右移动,以便['a','b','c','d']变为['d','a','b','c'][1,2,3]变为[3,1,2].

我尝试了以下,但它不起作用:

def shift(aList):
    n = len(aList)
    for i in range(len(aList)):
        if aList[i] != aList[n-1]:
            aList[i] = aList[i+1]
             return aList
         elif aList[i] == aList[i-1]:
            aList[i] = aList[0]
            return aList
shift(aList=[1,2,3])
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 9

如果您对切片符号过敏: a.insert(0,a.pop())

用法:

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]
Run Code Online (Sandbox Code Playgroud)


Sam*_*uns 7

如果您尝试移动元素,请使用方法:collections.deque rotate

#! /usr/bin/python3

from collections import deque
a = deque([1, 2, 3, 4])
a.rotate()
print(a)
Run Code Online (Sandbox Code Playgroud)

结果:

[2, 3, 4, 1]
Run Code Online (Sandbox Code Playgroud)


小智 7

你可以使用这个:

li=li[-1:]+li[:-1]
Run Code Online (Sandbox Code Playgroud)


mkr*_*er1 6

您可以将负索引与列表串联一起使用:

def shift(seq, n=0):
    a = n % len(seq)
    return seq[-a:] + seq[:-a]
Run Code Online (Sandbox Code Playgroud)


dot*_*hen 5

您可以将列表中的最后一个元素切片,然后将其添加到新列表的开头:

aList = [aList[-1]] + aList[:-1]
Run Code Online (Sandbox Code Playgroud)

结果如下:

>>> aList = [1,2,3]
>>> aList = [aList[-1]] + aList[:-1]
>>> aList
[3, 1, 2]
Run Code Online (Sandbox Code Playgroud)