Python 将文件中的单词与列表进行比较太慢

Python 将文件中的单词与列表进行比较太慢,python,Python,我想写一个函数,它接受一个单词列表(wordlist),打开一个txt文件并返回一个txt文件中没有出现的单词列表。这就是我目前所拥有的 def check_words_in_file(wordlist): """Return a list of words that don't appear in words.txt""" words = set() words = open("words.txt").read().splitlines() return [x

我想写一个函数,它接受一个单词列表(wordlist),打开一个txt文件并返回一个txt文件中没有出现的单词列表。这就是我目前所拥有的

def check_words_in_file(wordlist):
    """Return a list of words that don't appear in words.txt"""
    words = set()
    words = open("words.txt").read().splitlines()

    return [x for x in wordlist if x not in words]

这个函数的问题是速度太慢。如果我使用一个由10000个单词组成的词表,大约需要15秒来完成。如果我用一个300000,它需要的时间比它应该要长。还有什么方法可以让这个函数更快吗?

问题在于你对变量的使用和与对象的关联的理解,这在你写的时候很明显

words = set()
words = open("words.txt").read().splitlines()
在第一行中,首先创建一个空集对象,并将其引用与变量
words
关联。稍后打开文件并拆分其内容行,这将返回一个列表,并将变量
words
与列表重新绑定

你可能打算写

words = set(open("words.txt").read().splitlines())
进一步改进

若您创建一组参数
wordlist
,并找到一个非对称的集合差异,您实际上可以做得更好

words = set(wordlist).difference(open("words.txt").read().splitlines())
return list(words)
吹毛求疵

通常不建议打开文件并对文件句柄进行垃圾收集。关闭文件或使用上下文管理器

with open("words.txt") as fin:
    from itertools import imap
    words = set(wordlist).difference(imap(str.strip, fin))
    return list(words)

以后请尝试选择描述性标题。如果每个有Python问题的人都使用“Python编程”作为标题,那么我们将有将近350000个相同标题的问题,没有人能找到任何东西。非常感谢您澄清这一点!干杯