Skip to main content
 首页 » 编程设计

python之如何在 for 循环中删除迭代器对象的元素

2025年05月04日15shanyou

这个 super 简单

import xml.etree.ElementTree as ET 
tree = ET.parse('country_data.xml') 
root = tree.getroot() 
delete = False 
for child in root: 
    if delete: 
        root.remove(child) 
        continue 
    if child.getchildren(): 
        delete = True 

我想要的是保留第一个 child 并删除所有后续 child 。

但这里只删除了“交替”元素。

我们可以使用正常的序列

for child in root[:]: 

或者在我们可以使用的对象的情况下

from copy import deepcopy 
for child in deepcopy(root): 

但是如果我这样做,我不会得到“root”的子实例,而只会得到副本的子实例,所以我不能用它来删除 root 的子实例。

有什么想法吗?

PS:我使用 child.getchildren() 因为我需要保留第一个有自己 child 的 child 。

编辑

受以下 Ashalynd 评论的启发,我尝试了简单的切片

for child in root[:]: 

成功了。我一直在想,因为 root 是一个实例,切片将不起作用。

但现在我想知道为什么以下内容不起作用?

from copy import copy 
for child in copy(root): 

因为浅拷贝本质上是对自身进行切片。

请您参考如下方法:

如果您需要在某个点之后停止:

for i, child in enumerate(root): 
    if child.getchildren(): 
        pruned_children = root[:i] 
        break 

然后从那时起就使用pruned_children。