Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何删除for循环中迭代器对象的元素_Python - Fatal编程技术网

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

Python 如何删除for循环中迭代器对象的元素,python,Python,这非常简单 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 我想要的是保留

这非常简单

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
我想要的是保留第一个孩子,并删除所有后续的孩子

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

对于正常序列,我们可以使用

for child in root[:]:
或者是我们可以使用的物品

from copy import deepcopy
for child in deepcopy(root):
但是如果我这样做,我不会得到'root'的子实例,而是副本的唯一子实例,因此我不能用它来删除root的子实例

有什么想法吗

注:我使用
child.getchildren()
,因为我需要保留第一个有自己孩子的孩子

编辑

受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

对于根目录[1::]:
复制(根目录)
根目录[:]
不同。前者的类型是
xml.etree.ElementTree.Element
;后者的类型是
list
,但这在
for
循环中并不重要。元素本质上是相同的。删减的子元素将只是一个列表,而不是元素类型的实例。@martineau我也认为相同的根切片不起作用。但它奏效了。有人能解释它是如何工作的吗?@Jibin:显然
elementtree
Element
对象支持索引和切片(请参阅)。所以这是可能的,因为
getroot()
返回一个
元素
实例。@Jibin根据您的编辑切片工作,我将更新我的答案以反映您的编辑。看一看,如果你很高兴,那就接受吧。@Al.Sal试试你的切片例子。d=c[:]。它给出了完全相同的结果。