Python列表基本操作
因此,我试图编写一个非常基本的函数,可以将列表中的每个元素提前移动一个索引。我想我已经非常接近我想要的结果了 例如,如果列表是Python列表基本操作,python,python-3.x,Python,Python 3.x,因此,我试图编写一个非常基本的函数,可以将列表中的每个元素提前移动一个索引。我想我已经非常接近我想要的结果了 例如,如果列表是 l = [1, 2, 4, 5, 'd'] 我希望以后会是这样 l = [2, 4, 5, 'd', 1] 我的代码的真实性 l = [2, 4, 5, 1, 1] 这是我的代码,我只是不知道这里发生了什么,在很多随机尝试更改代码之后 提前谢谢你们 def cycle(input_list): count = 0 while count < len(inpu
l = [1, 2, 4, 5, 'd']
我希望以后会是这样
l = [2, 4, 5, 'd', 1]
我的代码的真实性
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
def循环(输入列表):
计数=0
当计数
以下是我要做的。获取列表的第一项,将其删除,然后将其添加回末尾
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
作为一名python开发人员,我真的忍不住要键入这一行
newlist=input[start:][input[:start]
其中start
是您必须旋转列表的数量
例:
input=[1,2,3,4]
您想按2
,start=2
输入[2:][3,4]
输入[:2]=[1,2]
newlist=[3,4,1,2]
您可以这样做(就地):
以功能形式(制作副本):
您可以使用
while
或for
语句执行此操作。
对使用:
newList = []
for index in range(1, len(list)):
newList.append(list[index])
newList.append(list[0])
在
时使用:
newList = []
index = 1
while index < len(list):
newList.append(list[index])
index += 1
newList.append(list[0])
您从不使用tmp变量。您需要在while循环之外定义它,然后实际使用它。l.append(l.pop(0))
:)pop(0)
已经返回项目,不需要单独获取第一个项目。这不会复制l
,如果要创建副本,您需要ret=l[:]
。@Holt或者ret=list(l)
@Holt谢谢。我忘了它只是分配了一个新的句柄/变量。换了。
newList = []
for index in range(1, len(list)):
newList.append(list[index])
newList.append(list[0])
newList = []
index = 1
while index < len(list):
newList.append(list[index])
index += 1
newList.append(list[0])
def move(list):
newList = []
for index in range(1, len(list)):
newList.append(list[index])
newList.append(list[0])
return newList
list = [1, 2, 3, 4, 5, 'd']
list = move(list)
print(list)
>>>[2, 3, 4, 5, 'd', 1]