如何在 for 循环中加速?如何提高代码的性能?

유한정*_*유한정 1 python performance for-loop

我想提高我的代码的性能。我之前按照建议尝试了几种方法,但是我的代码速度仍然很慢。我可以做什么而不是尝试我尝试过的方式?

我的代码在这里:

matched_word = []
for w in word_list:
    for str_ in dictionary:
        if str_ == w:
            matched_word.append(str_)
Run Code Online (Sandbox Code Playgroud)

这里有一些参考点:

  • 首先word_list的长度是160000,dictionary的长度大约是200000。
  • 其次,我不能使用一组 word_list,因为我想制作一个matched_word包含重复词( 的元素word_list)的列表 ( )。
  • 第三,以下代码仍然运行缓慢。
import collections
matched_word = collections.deque
for w in dictionary:
    if w in word_list:
        matched_word.append(w)
Run Code Online (Sandbox Code Playgroud)
  • 第四,下面的代码仍然运行缓慢。
matched_word = [w for w in word_list if w in dictionary]
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。(也感谢所有之前提供建议的人。)

che*_*ner 5

你不需要遍历字典;只需检查是否w是钥匙。您正在将 O(1) 查找变成 O(n) 扫描。

matched_word = [w for w in word_list if w in dictionary]
Run Code Online (Sandbox Code Playgroud)