【发布时间】:2021-07-21 14:02:16
【问题描述】:
我想提高我的代码的性能。我之前按照建议尝试了几种方法,但是我的代码速度仍然很慢。除了尝试我尝试过的方式,我还能做什么?
我的代码在这里:
matched_word = []
for w in word_list:
for str_ in dictionary:
if str_ == w:
matched_word.append(str_)
这里有一些参考点:
- 首先,word_list的长度为160,000,dictionary的长度约为200,000。
- 其次,我不能使用一组 word_list,因为我想制作一个包含重复单词(
word_list的元素)的列表 (matched_word)。 - 第三,下面的代码仍然运行缓慢。
import collections
matched_word = collections.deque
for w in dictionary:
if w in word_list:
matched_word.append(w)
- 第四,下面的代码也依然运行缓慢。
matched_word = [w for w in word_list if w in dictionary]
感谢您的帮助。 (也感谢所有之前提供建议的人。)
【问题讨论】:
-
请使用
word_list和dictionary的示例更新您的代码。 -
您是否尝试过使用
numpy数组而不是列表?这可以加快性能
标签: python performance for-loop