【问题标题】:How can I speed up in for-loop? How can I improve the performance of code?如何在 for 循环中加快速度?如何提高代码的性能?
【发布时间】: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_listdictionary 的示例更新您的代码。
  • 您是否尝试过使用numpy 数组而不是列表?这可以加快性能

标签: python performance for-loop


【解决方案1】:

您不需要遍历字典;只需检查 w 是否是键。您正在将 O(1) 查找转换为 O(n) 扫描。

matched_word = [w for w in word_list if w in dictionary]

【讨论】:

    【解决方案2】:

    我不能使用 word_list 集合,因为我想创建一个列表(=matched_word),包括重复的单词(= word_list 的元素)。

    由于lists在python中的实现方式.appending可能需要较长的时间,由于上述要求,set不是可选的,但是python标准库中有专门开发的结构可以快速插入最后,即来自collections 内置模块的collections.deque。示例用法

    import collections
    matched_word = collections.deque()
    for w in ["A","B","C","A","B"]:
        matched_word.append(w)
    matched_word_list = list(matched_word)
    print(matched_word_list)
    

    输出

    ['A', 'B', 'C', 'A', 'B']
    

    【讨论】:

    • 追加到列表已经很快了;在列表的 开头 插入速度很慢。 deque 进行了优化,可以在 任一端 端快速插入(尽管在任一端的中间插入仍然较慢)。
    猜你喜欢
    • 2020-11-03
    • 2020-10-21
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多