Python 3.6
我想从字符串中删除字符串列表。这是我第一次失败的尝试:string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']
result = list(filter(lambda x: x not in items_to_remove, string.split(' ')))
print(result)
输出:
^{pr2}$
但是如果x间隔不好,这就行不通了。我觉得一定有一个内置的解决方案,嗯,一定有更好的办法!在
我已经看了这个关于堆栈溢出的discussion,和我一样的问题。。。在
不要浪费我的努力。我计时了所有的解决方案。我相信最简单、最快、最具Python特征的就是简单的for循环。这不是另一篇文章的结论。。。在result = string
for i in items_to_remove:
result = result.replace(i,'')
测试代码:import timeit
t1 = timeit.timeit('''
string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']
result = list(filter(lambda x: x not in items_to_remo