Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串中删除多个子字符串的最有效方法?_Python_String_Performance - Fatal编程技术网

Python 从字符串中删除多个子字符串的最有效方法?

Python 从字符串中删除多个子字符串的最有效方法?,python,string,performance,Python,String,Performance,从字符串中删除子字符串列表的最有效方法是什么 我想要一种更干净、更快的方法来完成以下工作: 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.repl

从字符串中删除子字符串列表的最有效方法是什么

我想要一种更干净、更快的方法来完成以下工作:

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)
正则表达式:

上面的一行代码实际上没有您的
字符串快。请替换
版本,但一定要短一些:

>>> 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+
单词
字符串中过滤出单词,并将其与一组
替换列表进行比较(是的,实际的
集合
集合(替换列表)
):


对于更大的字符串和单词,请使用
字符串。替换
方法,我的第一个解决方案将以二次时间结束,但解决方案应以线性时间运行。

如果列表是
['apple','banana']
,字符串是
'banappleana'
,那么它应该变成
'
还是
'banana'
?您当前的代码将生成
。这肯定更干净,但速度更快吗?这正是我所想的@CyberneticWerkGuruorc:不知道,但它肯定没有banappleana问题。@CyberneticWerkGuruorc事实证明它很慢,增加了一个更快的版本。@AshwiniChaudhary很大的改进+1.
>>> 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
>>> 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