我想要将列表中的元素进行旋转,例如向右移动列表元素,使得['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])
a[:] = a[1:] + a[:1]
对于移动任意数量(n)的元素:a[:] = a[n:] + a[:n]
- AChampion