首页 > 解决方案 > 将单词列表与句子列表进行比较并打印匹配行的 Pythonic 方法

问题描述

我目前正在清理我们的数据库,它变得非常耗时。典型的

for email in emails:   

循环在任何地方都不够快。

例如,我目前正在将 230,000 封电子邮件列表与 39,000,000 行完整记录列表进行比较。将这些电子邮件与它们所属的记录行匹配并打印需要几个小时。有谁知道如何在此查询中实现线程以加快速度?虽然这是超级快

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

那永远不会打印匹配的线,只会打印针。

先感谢您

标签: python

解决方案


一种可能性是使用 aset来存储电子邮件。这使得检查if word in emails O(1)。因此,完成的工作与文件中的总字数成正比:

emails = {"string1", "string2", "string3"} # this is a set

for line in f:
    if any(word in emails for word in line.split()):
        print("yay!")

您最初的解决方案是O(nm)(对于n 个单词和m个电子邮件),而不是O(n)set.


推荐阅读