gpt4 book ai didi

python - 遍历列表删除项目,一些项目没有被删除

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

我正在尝试将一个列表的内容转移到另一个列表,但它不起作用,我不知道为什么。我的代码如下所示:

list1 = [1, 2, 3, 4, 5, 6]
list2 = []

for item in list1:
list2.append(item)
list1.remove(item)

但如果我运行它,我的输出将如下所示:

>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]

我想我的问题有三个方面:为什么会发生这种情况,如何让它发挥作用,以及我是否忽略了一个非常简单的解决方案,例如“移动”语句或其他东西?

最佳答案

原因是您要从第一个列表中(附加和)删除,从而使它变小。因此迭代器在遍历整个列表之前停止。

要实现你想要的,请执行以下操作:

list1 = [1, 2, 3, 4, 5, 6]
list2 = []

# You couldn't just make 'list1_copy = list1',
# because this would just copy (share) the reference.
# (i.e. when you change list1_copy, list1 will also change)

# this will make a (new) copy of list1
# so you can happily iterate over it ( without anything getting lost :)
list1_copy = list1[:]

for item in list1_copy:
list2.append(item)
list1.remove(item)

list1[start:end:step]slicing syntax :当您将 start 留空时,它默认为 0,当您将 end 留空时,它是可能的最高值。所以 list1[:] 表示其中的所有内容。 (感谢 Wallacoloo)

就像一些人说的那样,如果这是您的意图,您也可以使用 list 对象的 extend 方法将一个列表复制到另一个列表。 (但是我选择了上面的方式,因为这和你的方式比较接近。)

由于您是 Python 的新手,我有一些东西给您:Dive Into Python 3 - 它是免费和容易的。 - 玩得开心!

关于python - 遍历列表删除项目,一些项目没有被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541528/

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