迭代列表删除项目,一些项目不会被删除

pot*_*bed 7 python list

我正在尝试将一个列表的内容转移到另一个列表,但它不起作用,我不知道为什么不.我的代码看起来像这样:

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

for item in list1:
    list2.append(item)
    list1.remove(item)
Run Code Online (Sandbox Code Playgroud)

但如果我运行它,我的输出看起来像这样:

>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)

我的问题有三个,我猜:为什么会发生这种情况,如何让它发挥作用,我是否会忽略一个非常简单的解决方案,如"移动"声明或其他什么?

Chr*_*heD 8

当你迭代它时,你正在从list1中删除项目.

那是在惹麻烦.

试试这个:

>>> list1 = [1,2,3,4,5,6]
>>> list2 = []
>>> list2 = list1[:] # we copy every element from list1 using a slice
>>> del list1[:] # we delete every element from list1
Run Code Online (Sandbox Code Playgroud)

  • 不需要list2 = [] (2认同)

Jos*_*hua 8

原因是你从第一个列表中删除(追加和删除),因此它会变小.因此迭代器在整个列表可以通过之前停止.

要实现您的目标,请执行以下操作:

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)
Run Code Online (Sandbox Code Playgroud)

list1[start:end:step]切片语法:当你离开开始为空时它默认为0,当你把结尾留空时它是最高可能的值.所以list1 [:]意味着其中的一切.(感谢Wallacoloo)

就像一些家伙说的那样,你也可以使用extend-object的-method list将一个列表复制到另一个列表,如果这是你的意图.(但我选择了上面的方法,因为这接近你的方法.)

因为你是python的新手,我有适合你的东西:潜入Python 3 - 它是免费且简单的.- 玩得开心!