[英]Most efficient way to remove multiple substrings from string?
從字符串中刪除子串列表的最有效方法是什么?
我想要一個更清潔,更快捷的方法來做到以下幾點:
words = 'word1 word2 word3 word4, word5'
replace_list = ['word1', 'word3', 'word5']
def remove_multiple_strings(cur_string, replace_list):
for cur_word in replace_list:
cur_string = cur_string.replace(cur_word, '')
return cur_string
remove_multiple_strings(words, replace_list)
正則表達式:
>>> import re
>>> re.sub(r'|'.join(map(re.escape, replace_list)), '', words)
' word2 word4, '
上面的單string.replace
實際上沒有你的string.replace
版本快,但肯定更短:
>>> words = ' '.join([hashlib.sha1(str(random.random())).hexdigest()[:10] for _ in xrange(10000)])
>>> replace_list = words.split()[:1000]
>>> random.shuffle(replace_list)
>>> %timeit remove_multiple_strings(words, replace_list)
10 loops, best of 3: 49.4 ms per loop
>>> %timeit re.sub(r'|'.join(map(re.escape, replace_list)), '', words)
1 loops, best of 3: 623 ms per loop
天哪! 快了近12倍。
但我們可以改進它嗎? 是。
因為我們只關心單詞,我們可以做的只是使用\\w+
過濾words
字符串中的words
,並將其與一組replace_list
(是實際set
: set(replace_list)
)進行比較:
>>> def sub(m):
return '' if m.group() in s else m.group()
>>> %%timeit
s = set(replace_list)
re.sub(r'\w+', sub, words)
...
100 loops, best of 3: 7.8 ms per loop
對於更大的字符串和單詞, string.replace
方法和我的第一個解決方案將最終采用二次時間,但解決方案應該以線性時間運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.