从列表列表中删除第n行 - Python

时间:2017-05-13 10:23:53

标签: python xml python-3.x elementtree

我的要求是删除包含任何带有文本“Podcast”的元素的行。 audio是xml元素列表的列表

 for i in range(len(audio)):
        for j in range(len(audio[i])):
            if audio[i][j].text=="Podcast":
                del audio[i]

我收到错误:IndexError:列表索引超出范围 但是我能够打印出我想要删除的相同内容。

for i in range(len(audio)):
    for j in range(len(audio[i])):
        if audio[i][j].text=="Podcast":
            print(audio[i])

结果:

[<Element 'key' at 0x043253C0>, <Element 'integer' at 0x043253F0>, <Element 'key' at 0x04325420>, <Element 'string' at 0
x04325450>, <Element 'key' at 0x04325480>, <Element 'string' at 0x043254B0>, <Element 'key' at 0x043254E0>, <Element 'st
ring' at 0x04325510>, <Element 'key' at 0x04325540>, <Element 'string' at 0x04325570>, <Element 'key' at 0x043255A0>, <E
lement 'string' at 0x043255D0>, <Element 'key' at 0x04325600>, <Element 'integer' at 0x04325630>, <Element 'key' at 0x04
325660>, <Element 'integer' at 0x04325690>, <Element 'key' at 0x043256C0>, <Element 'integer' at 0x043256F0>, <Element '
key' at 0x04325720>, <Element 'date' at 0x04325750>, <Element 'key' at 0x043257B0>, <Element 'date' at 0x043257E0>, <Ele
ment 'key' at 0x04325840>, <Element 'integer' at 0x04325870>, <Element 'key' at 0x043258A0>, <Element 'integer' at 0x043
258D0>, <Element 'key' at 0x04325900>, <Element 'integer' at 0x04325930>, <Element 'key' at 0x04325960>, <Element 'integ
er' at 0x04325990>, <Element 'key' at 0x043259C0>, <Element 'date' at 0x043259F0>, <Element 'key' at 0x04325A50>, <Eleme
nt 'date' at 0x04325A80>, <Element 'key' at 0x04325AE0>, <Element 'integer' at 0x04325B10>, <Element 'key' at 0x04325B40
>, <Element 'string' at 0x04325B70>, <Element 'key' at 0x04325BD0>, <Element 'string' at 0x04325C00>, <Element 'key' at
0x04325C30>, <Element 'true' at 0x04325C60>, <Element 'key' at 0x04325C90>, <Element 'true' at 0x04325CC0>, <Element 'ke
y' at 0x04325CF0>, <Element 'string' at 0x04325D20>, <Element 'key' at 0x04325D50>, <Element 'integer' at 0x04325DB0>, <
Element 'key' at 0x04325DE0>, <Element 'integer' at 0x04325E40>]

2 个答案:

答案 0 :(得分:3)

result = [row for row in audio if not "Podcast" in row]

这意味着所有行都带有&#34; Podcast&#34;在它将被删除。

答案 1 :(得分:1)

如果在迭代时更改列表,则会产生索引错误等副作用。

您应该使用具有正确条件的列表理解。

您的条件是一行中的所有元素都没有audio = [row for row in audio if not any(item.text == "Podcast" for item in row)] 作为项目。所以你的代码可能就像

Shop