Python遍历列表后删除列表中一半的元素 [英] Python deleting half the elements in a list after iterating through it

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

问题描述

我已经完全被这一迷住了:

I've been completely stumped on this one:

我有以下python代码:

I have the following python code:

def remove(self, widgets):
    for widget in widgets:
        widget_found = False
        for widget_sig in self.widgets:
            if widget_sig.id == widget:
                #remove all objects from selected widget
                widget_found = True
                to_remove = widget_sig.objs
                for obj in to_remove:
                    #objs are all intances of oo_canvas classes
                    obj.destroy()
                    self._build(widget, obj)
        if not widget_found:
            #if we iterated through the entire list and still couldn't find anything
            raise mockingbird_errs.InternalMockingbirdError("The requested widget was not registered with this builder: "+str(widget))

这应该很简单.问题是,它永远不会正确地迭代to_remove.由于某种原因,它会跳过所有其他元素.更令人困惑的是,如果我让它在for循环之前和之后输出to_remove的长度,那么它会输出254和127.据我所知,遍历列表并不涉及删除其他所有元素.

This should be pretty straight forward. The thing is, it never iterates through to_remove correctly. For some reason, it skips every other element. Even more baffling, is if I have it print the length of to_remove before and after the for loop, it prints 254 and 127. Huh? As far as I know, iterating through a list does not involve deleting every other element.

我错过了一些简单的东西吗?到底是怎么回事?

Am I missing something straightforward? What on earth is going on?

推荐答案

...它会跳过所有其他元素.

... it skips every other element.

那是因为您一直在删除它们,将列表缩短了1.然后继续进行下一个索引.可以向后工作,或遍历列表的副本.

That's because you keep deleting them, shortening the list by 1. And then you move on to the next index. Either work backwards, or iterate over a copy of the list.

这篇关于Python遍历列表后删除列表中一半的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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