遍历列表删除项目,某些项目未删除 [英] iterating through a list removing items, some items are not removed

查看:75
本文介绍了遍历列表删除项目,某些项目未删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]切片语法:当您离开 start 为空,则默认为0,而当 end 为空时,则为最大可能值.因此list1 [:]表示其中的所有内容. (感谢Wallacoloo)

像某些帅哥说的那样,如果您打算这样做,也可以使用list对象的extend方法将一个列表复制到另一个. (但是我选择了上面的方法,因为这很接近您的方法.)

由于您是python的新手,所以我为您提供了一些帮助:深入Python 3 -免费,轻松. -玩得开心!

I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this:

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

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

But if I run it my output looks like this:

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

My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?

解决方案

The reason is that you're (appending and) removing from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through.

To achieve what you want, do this:

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)

The list1[start:end:step] is the slicing syntax: when you leave start empty it defaults to 0, when you leave end empty it is the highest possible value. So list1[:] means everything in it. (thanks to Wallacoloo)

Like some dudes said, you could also use the extend-method of the list-object to just copy the one list to another, if this was your intention. (But I choosed the way above, because this is near to your approach.)

As you are new to python, I have something for you: Dive Into Python 3 - it's free and easy. - Have fun!

这篇关于遍历列表删除项目,某些项目未删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆