Python pop和append并没有将列表1中的所有元素移动到列表2中

Python pop和append并没有将列表1中的所有元素移动到列表2中,python,Python,为什么pop和append不能完成整个循环?我的第一个猜测是pop没有重新调整原始列表的索引,但当我打印TXT[0]以确认它仍然位于最前面时,这似乎不是真的。我试图弄明白为什么下面的方法不起作用。多谢各位 txt = 'shOrtCAKE' txt = list(txt) new_list = [] for x in txt: value = txt.pop(0) new_list.append(value) print(new_list) print(txt) print(

为什么pop和append不能完成整个循环?我的第一个猜测是pop没有重新调整原始列表的索引,但当我打印TXT[0]以确认它仍然位于最前面时,这似乎不是真的。我试图弄明白为什么下面的方法不起作用。多谢各位

txt = 'shOrtCAKE'
txt = list(txt)
new_list = []

for x in txt:
    value = txt.pop(0)
    new_list.append(value)

print(new_list)
print(txt)
print(txt[0])

您不应该在迭代列表时修改它。相反,请使用此代码

for x in txt:
    value = x
    new_list.append(value)
txt = [] # assuming you want txt to be empty for some reason
但是,如果您最终打印txt[0],则会出现错误,因为列表索引将超出范围

然而,你真的不需要循环。只需执行以下操作:

new_list = txt[:] # [:] ensures that any changes done to txt won't reflect in new_list

您不应该在迭代列表时修改它。相反,请使用此代码

for x in txt:
    value = x
    new_list.append(value)
txt = [] # assuming you want txt to be empty for some reason
但是,如果您最终打印txt[0],则会出现错误,因为列表索引将超出范围

然而,你真的不需要循环。只需执行以下操作:

new_list = txt[:] # [:] ensures that any changes done to txt won't reflect in new_list

您不应该从正在迭代的列表中删除元素。在本例中,您甚至没有使用迭代期间获得的列表值

如果您仍然想使用pop,则有多种可能性,这不涉及对txt的迭代。例如:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list
循环在开始时计算的固定次数: txt不为空时循环: 循环直到pop失败: 当然,你不必使用流行音乐。您可以这样做,例如:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list

您不应该从正在迭代的列表中删除元素。在本例中,您甚至没有使用迭代期间获得的列表值

如果您仍然想使用pop,则有多种可能性,这不涉及对txt的迭代。例如:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list
循环在开始时计算的固定次数: txt不为空时循环: 循环直到pop失败: 当然,你不必使用流行音乐。您可以这样做,例如:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list

不要修改正在迭代的列表。在循环列表时,您正在更改列表。档案中有很多关于这方面的问题。这可能会有所帮助。不要修改正在迭代的列表。在循环列表时,您正在更改列表。档案中有很多关于这方面的问题。这可能会有所帮助。