Python Loop运行时间非常长



我正在尝试从一组字符串中列出词汇列表,然后删除该集合中至少30个字符串中未重复的所有单词。该集合中总共有大约300,000个单词。由于某种原因,检查是否在整个30次中重复一个单词的代码至少超过5分钟,我想知道如何使该代码更有效,因此它具有合理的运行时。谢谢!

word_list = []
for item in ex_set:
    word_list += (list(dict.fromkeys(item.split()))) #remove unique words
vocab_list = []
for word in word_list: #where it runs forever
    if word_list.count(word) >= 30:
        vocab_list.append(word)

如果要在出现至少30次的单词列表中获取所有单词,则可以先使用collections.Counter来计算它们30次。

from collections import Counter
word_counts = Counter(ex_set)
vocab_list = [word for word, count in words.items() if count >= 30]

只是另一个注意事项,请勿使用 set单词作为变量名称,因为它是关键字

这是思考问题的另一种方式:

再次在整个列表上循环count循环(二次时间(。

如果构建单词计数的dict,这是一个较小的数据结构,可以检查第二个迭代:

from collections import defaultdict
counter_dict = defaultdict(int)
for word in word_list:
    counter_dict[word] += 1
vocab_list = []
for word, count in counter_dict.items()
    if count >= 30:
        vocab_list.append(word)

看过jmonsky的答案,如果有效,则应接受。

最新更新