我需要在for循环中排除列表中的元素,并通过使用python搜索排除的元素来更新xml文件

问题描述 投票:0回答:1

我需要在for循环中排除列表中的元素,并通过使用该排除元素进行搜索来更新xml文件。

下面是我的xml文件run.xml

<stm>
    <id>ignore</id>
    <ari>dv</rid>
    <session>test</session>
</stm>

我有一个列表test = ['dv', 'ab', 'abc']

for i in test:
    print i
    "here I need to exclude the current element(i) from the list(test)"
    "so the list will become for the first loop ['ab', 'abc']"
    "assign excluded list to variable"
    "next I need to search for current element(i) in the given xml file if found, update the next line 'test' with the 'temp'"

我用谷歌搜索但没有找到任何相关的解决方案

更新xml文件后,输出应如下所示

<stm>
    <id>ignore</id>
    <ari>dv</rid>
    <session>temp</session>
</stm>

python list for-loop skip
1个回答
0
投票

我怀疑有更好的方法可以解决你想要做的事情,但这里有一些方法可以解决你的问题:

如果要为for循环中的每个元素创建一个包含exclude元素的列表:

>>> x = [1, 2, 3]
>>> for i in x:
...     l = [j for j in x if j !=i]
...     print(l)
...
[2, 3]
[1, 3]
[1, 2]

如果要永久删除列表中的值:

>>> for i in x[:]:
...     #this is important to iterate over a copy of the whole list in case you remove elements that you want to use
...     x.remove(i)
...     print(x)
...
[2, 3]
[3]
[]

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.