从列表中删除所有出现的字符串

时间:2018-04-11 22:21:26

标签: python

有人请告诉我有更简洁的方式来写这个!?我想删除所有'功能& amp;优点&#39 ;.必须有更简洁的方法为列表中的字符串执行此操作。

lov_headers = [x.find('displayname').text for x in soup.find_all('attributedefinition')]


if 'Part number' in lov_headers:
    lov_headers.remove('Part number')
if 'Product Features' in lov_headers:
    lov_headers.remove('Product Features')
if 'Packaging' in lov_headers:
    lov_headers.remove('Packaging')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')

2 个答案:

答案 0 :(得分:1)

将要删除的内容放入set(),然后使用列表推导过滤掉您不想要的结果:

to_remove = set(['Part number', 'Features & Benefits', 'Product Features', 'Packaging'])

new_list = [i for i in lov_headers if i not in to_remove]

答案 1 :(得分:1)

您可以使用while循环:

while 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')