我正在尝试从一组字符串中创建词汇list,然后删除集合中至少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)
分析解答

如果你试图让list中的所有单词出现至少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这个词作为变量名,因为它是一个关键字