Python列表基本操作

2024-09-28 21:13:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图编写一个非常基本的函数,可以将列表中的每个元素提前一个索引移动。我想我已经接近我想要的结果了。在

例如,如果列表是

l = [1, 2, 4, 5, 'd']

我希望以后能这样

^{pr2}$

我的代码的真实性

l = [2, 4, 5, 1, 1]

这是我的代码,我只是不知道在多次尝试更改代码之后发生了什么。。。在

提前谢谢你们!在

def cycle(input_list):
count = 0
while count < len(input_list):
     tmp = input_list[count - 1]
     input_list[count - 1] = input_list[count]
     count+=1

Tags: 函数代码元素列表inputlendefcount
3条回答

这就是我要做的。获取列表的第一项,删除它,然后将其添加回末尾。在

def cycle(input_list):
    first_item = input_list.pop(0)  #gets first element then deletes it from the list 
    input_list.append(first_item)  #add first element to the end

你可以这样做(就地):

l.append(l.pop(0))

函数形式(复制):

^{pr2}$

作为一个python开发人员,我真的忍不住要输入这一行代码

newlist = input[start:] + input[:start]

其中start是必须旋转列表的数量

例如:

input = [1,2,3,4]

您想按2start = 2移动数组

input[2:] = [3,4]

input[:2] = [1,2]

newlist = [3,4,1,2]

相关问题 更多 >