python怎么遍历列表剩余的元素,Python遍历列表后删除列表中一半的元素

I've been completely stumped on this one:

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))

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值