유한정*_*유한정 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)
这里有一些参考点:
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)
谢谢你的帮助。(也感谢所有之前提供建议的人。)
你不需要遍历字典;只需检查是否w是钥匙。您正在将 O(1) 查找变成 O(n) 扫描。
matched_word = [w for w in word_list if w in dictionary]
Run Code Online (Sandbox Code Playgroud)