[New-bugs-announce] [issue41899] Poor example for Element.remove()
WoodyWoo
report at bugs.python.org
Wed Sep 30 20:08:35 EDT 2020
New submission from WoodyWoo <saulmatchless at 163.com>:
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 at python
components: Documentation
messages: 377726
nosy: WoodyWoo, docs at python
priority: normal
severity: normal
status: open
title: Poor example for Element.remove()
type: behavior
versions: Python 3.8
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41899>
_______________________________________
More information about the New-bugs-announce
mailing list