小编nes*_*man的帖子

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)

python

6
推荐指数
5
解决办法
3万
查看次数

标签 统计

python ×1