为什么for循环中的del list [0]仅删除列表的一半? [英] Why does del list[0] in a for-loop only delete half the list?

查看:93
本文介绍了为什么for循环中的del list [0]仅删除列表的一半?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,并且仅使用for循环删除列表的一半.为什么会这样?另外,如何遍历列表中的第一个元素?

  list = [1,2,3,4,5,6,7,8,9,10]对于列表中的x:打印清单[0]删除列表[0]打印清单 

输出:

  12个345[6、7、8、9、10] 

解决方案

问题是您从列表中删除,但列表迭代器不知道该列表,并愉快地处理了剩余"列表.

因此,在第一次迭代中,迭代器位于索引0处,并且您删除了索引0;在下次迭代中,迭代器返回了索引1(在删除第一个项目之前,它就是索引2处的项目),并且它删除了索引0在下一次迭代中,您将获得索引2处的项目(最初是索引4,但是由于删除了两个项目,现在索引2),依此类推.最后,只要您为原始列表中间(一半)中处理的每个项目都删除一个项目,则索引一旦大于列表中剩余的项目,它就会停止.

长话短说:请勿修改您要遍历的列表.


如果您确实想执行类似的操作,则可以使用 while 循环:

  lst = [1,2,3,4,5,6,7,8,9,10]while lst:#只要lst包含项目打印lst [0]del lst [0]打印第一 

或遍历副本:

  lst = [1,2,3,4,5,6,7,8,9,10]对于lst [:]中的x:#[:]制作列表的浅表副本打印lst [0]删除列表[0]打印第一 

注意: list 是Python内置函数的名称,因此,如果您有一个具有相同名称的变量,则将隐藏该函数.这就是为什么我将变量名称更改为 lst .

I have the following code and it only deletes half the list using a for loop. Why does this happen? Also, how should I delete the first element of the list WHILE traversing through it?

list = [1,2,3,4,5,6,7,8,9,10]
for x in list:
    print list[0]
    del list[0]
print list 

Output:

1 
2
3
4
5
[6, 7, 8, 9, 10]

解决方案

The problem is that you delete from the list but the list-iterator doesn't know that and happily processes the "remaining" list.

So in the first iteration the iterator is at index 0 and you remove index 0, in the next iteration the iterator returns index 1 (which would be the item at index 2 before you removed the first item) and it removes index 0. In the next iteration you get the item at index 2 (which was at index 4 originally but since you removed two items is now at index 2) and so on. Finally it will stop as soon as the index is greater than the items remaining in the list, given that you remove one item for each item processed that's in the middle (half) of the original list.

Long story short: Don't modify the list you're iterating over.


If you really want to do something like that then you could use a while loop:

lst = [1,2,3,4,5,6,7,8,9,10]
while lst:   # as long as the lst contains items
    print lst[0]
    del lst[0]
print lst 

or iterate over a copy:

lst = [1,2,3,4,5,6,7,8,9,10]
for x in lst[:]:   # [:] makes a shallow copy of a list
    print lst[0]
    del lst[0]
print lst 

Note: list is the name of a built-in function of Python, so you would shadow this function if you have a variable with the same name. That's why I changed the variable name to lst.

这篇关于为什么for循环中的del list [0]仅删除列表的一半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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