蟒蛇 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)
Run Code Online (Sandbox Code Playgroud)
输出:
['test']
Run Code Online (Sandbox Code Playgroud)
但这不起作用,如果 x间隔不合适,。我觉得一定有内置解决方案,嗯一定有更好的方法!
我看过这个关于堆栈溢出的讨论,我的确切问题......
不要浪费我的努力。我为所有解决方案计时。我相信最简单、最快和最 Pythonic 的是简单的 for 循环。这不是另一个帖子中的结论......
result = string
for i in items_to_remove:
result = result.replace(i,'')
Run Code Online (Sandbox Code Playgroud)
测试代码:
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_remove, string.split(' ')))
''', number=1000000)
print(t1)
t2 = timeit.timeit('''
string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']
def sub(m):
return '' if m.group() in items_to_remove else m.group()
result = re.sub(r'\w+', sub, string)
''',setup= 'import re', number=1000000)
print(t2)
t3 = timeit.timeit('''
string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']
result = re.sub(r'|'.join(items_to_remove), '', string)
''',setup= 'import re', number=1000000)
print(t3)
t4 = timeit.timeit('''
string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']
result = string
for i in items_to_remove:
result = result.replace(i,'')
''', number=1000000)
print(t4)
Run Code Online (Sandbox Code Playgroud)
输出:
1.9832003884248448
4.408749988641971
2.124719851741177
1.085117268194475
Run Code Online (Sandbox Code Playgroud)
string.split()如果您对字符串间距没有信心,可以使用。
string.split()和string.split(' ')工作有点不同:
In [128]: 'this is a test'.split()
Out[128]: ['this', 'is', 'a', 'test']
In [129]: 'this is a test'.split(' ')
Out[129]: ['this', '', '', '', '', 'is', '', '', 'a', 'test']
Run Code Online (Sandbox Code Playgroud)
前者分割你的字符串,没有任何多余的空字符串。
如果您想要更高的安全性,或者您的字符串可以包含制表符和换行符,那么还有另一种使用正则表达式的解决方案:
In [131]: re.split('[\s]+', 'this is \t a\ntest', re.M)
Out[131]: ['this', 'is', 'a', 'test']
Run Code Online (Sandbox Code Playgroud)
最后,我建议将您的查找列表转换为查找,set以便在您的过滤器中进行高效查找:
In [135]: list(filter(lambda x: x not in {'is', 'this', 'a', 'string'}, string.split()))
Out[135]: ['test']
Run Code Online (Sandbox Code Playgroud)
在性能方面,列表复合比过滤器快一点,虽然不那么简洁:
In [136]: [x for x in string.split() if x not in {'is', 'this', 'a', 'string'}]
Out[136]: ['test']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5137 次 |
| 最近记录: |