首页 > 解决方案 > Python - 从列表中的每个字符串中删除目标词

问题描述

例如,我有一个字符串列表

my_list = ['this is a string', 'this is also a string', 'another String']

而且我还有一个要从该列表中的每个字符串中删除的单词列表

remove = ['string', 'is']

我想从 my_list 中删除 remove 中的字符串。

我试过循环遍历每个列表

new_list = []

for i in my_list:
    for word in remove:
        x = i.replace(word, "")
        new_list.append(x)

但这只是返回每个原始句子。

标签: python

解决方案


l1=""
l2=[]
my_list = ['this is a string', 'this is also a string', 'another String']
remove = ['string', 'is']
for i in my_list:
    l1=""
    for j in i.split():
        if j not in remove:
            l1=l1+" " +j
    l2+=[l1]        
        
print(l2)

您的代码将给出输出 ['this is a ', 'th a string', 'this is also a ', 'th also a string', 'another String', 'another String']is每个单词中的 也被删除,这是不可取的。)您可以使用.split(),如上图所示。

输出将是:

[' this a', ' this also a', ' another String']

编辑:

要消除列表中每个元素中的空格,您可以运行一个for循环并使用.lstrip()


推荐阅读