gpt4 book ai didi

python - 向右移动列表元素,并将末尾的列表元素移动到开头

转载 作者:太空狗 更新时间:2023-10-29 22:06:40 26 4
gpt4 key购买 nike

我想旋转列表中的元素,例如- 将列表元素向右移动,这样 ['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])

最佳答案

您可以将负索引与列表连接一起使用:

def shift(seq, n=0):
a = n % len(seq)
return seq[-a:] + seq[:-a]

关于python - 向右移动列表元素,并将末尾的列表元素移动到开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com