python - 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)
但这只是返回每个原始句子。
解决方案
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()
推荐阅读
- c++ - 如何使用 fstream (C++) 将十六进制值读入整数
- docker - 来自同一映像的 Docker 容器无法按预期工作
- haskell - Scott Wlaschin ThinkOfNumber 示例
- php - PHP - 在函数内部使用 include/require_once
- javascript - 使用 JavaScript 将 markdown 转换为 HTML - 限制支持的语法
- php - PHP函数数组多次返回一条记录
- chicken-scheme - 鸡计划:生成表未绑定变量
- .net-core - AutoMapper 8.0 缺少 GetPropertyMaps
- unit-testing - 不要模拟域对象规则?
- http - HTTP 协议中允许多少个标头?