我有一个列表,其中包含许多我使用Beautiful Soup从html页面中提取的元素。 在这个列表中,我有许多具有相同子字符串的元素,我想提取包含该子字符串的每个元素。
我的列表如下:
[
u'File:Saddam Hussein (107).jpg',
u'Template:Fn (page does not exist)',
u'Template:Fn (page does not exist)',
u'Template:Fn (page does not exist)',
u'Template:Fn (page does not exist)',
u'Template:Fn (page does not exist)',
u'File:AlBakr.jpg',
... (and so on) ...
]
我想删除带有字符串"(页面不存在)"的元素。
关于我如何做到这一点的任何想法?
答案 0 :(得分:2)
使用列表理解:
>>> lis = [u'File:Saddam Hussein (107).jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'File:AlBakr.jpg', u'Template:Fn (page does not exist)', u'File:Chiracsaddam.jpg', u'File:Donald saddam.jpg', u'Template:Fn (page does not exist)', u'File:SaddamandCuellar.jpg.jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'File:SaddamBaghdadwalkabout.jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Kurdish Patriotic Front (page does not exist)', u'File:TrialSaddam.jpg', u'Mohammad Rashdan (page does not exist)', u'Emmanuel Ludot (page does not exist)', u'Marc Henzelin (page does not exist)', u'Adnan Khairallah Tuffah (page does not exist)', u'Nidal al-Hamdani (page does not exist)', u'Ali Hussein (page does not exist)', u'File:SaddamandRana.jpg.jpg', u'Saddam Kamel Majid (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)']
如果要修改原始列表:
>>> lis[:] = [item for item in lis if "(page does not exist)" not in item]
或创建新列表:
new_lis = [item for item in lis if "(page does not exist)" not in item]
答案 1 :(得分:0)
>>> for i in range(len(l)-1, 0, -1):
... if l[i].find('(page does not exist)') > -1:
... del (l[i])
...
>>> l
[u'File:Saddam Hussein (107).jpg']
>>>