New submission from WoodyWoo <[email protected]>:
We can remove elements using Element.remove(). Let’s say we want to remove all
countries with a rank higher than 50:
>>>
>>> for country in root.findall('country'):
... rank = int(country.find('rank').text)
... if rank > 50:
... root.remove(country)
...
>>> tree.write('output.xml')
When the original xml has over 2 country with rank>50,and they are one by one
neighborly siblings element,the upper code will delete the 1st 3rd 5th and more
odd No. country.
A proper example should be:
index=0
while index < len(root.findall("./*")):
rank = int (root[index].find("rank").text)
if rank>50:
root.remove(root[index])
index=index+0
continue
index=index+1
I think "for each in list" should not work by index,but should work by pointer
like thing,could be a list of pointers.
A finial solution should be like this --- when the "for each in list" was
acting,the pointers list would be fixed,and you need not to worry about the
"list" changing.
----------
assignee: docs@python
components: Documentation
messages: 377726
nosy: WoodyWoo, docs@python
priority: normal
severity: normal
status: open
title: Poor example for Element.remove()
type: behavior
versions: Python 3.8
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue41899>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com