Skip to main content
 首页 » 编程设计

python之我该如何优化这段代码以及一般如何优化 Python for 循环

2025年05月04日9think

我目前正在运行这段代码:

for dicword in dictionary: 
    for line in train: 
        for word in line: 
            if dicword == word: 
                pWord[i] = pWord[i] + 1 
    i = i + 1 

其中 dictionary 和 pWord 是相同大小的一维列表,而 train 是二维列表。

dictionary和train都很大,代码执行起来很慢。

一般情况下,如何优化这段特定的代码和这样的代码?

编辑: train 是一个包含大约 2000 个列表的列表,每个列表又包含从文档中提取的单个单词。 dictionary 是通过从所有 train 中提取每个唯一的单词创建的。

这里是字典的创建:

dictionary = [] 
for line in train: 
    for word in line: 
        if word not in dictionary: 
            dictionary.append(word) 

编辑 2: 每个列表中的内容示例:

[ ... , 'It', 'ran', 'at', 'the', 'same', 'time', 'as', 'some', 'other', 'programs', 'about', ...] 

请您参考如下方法:

您可以使用 Counter .

from collections import Counter 
 
train = [["big", "long", "list", "of", "big", "words"],  
         ["small", "short", "list", "of", "short", "words"]] 
 
c = Counter(word for line in train for word in line) 
 
>>> c 
Counter({'big': 2, 
         'list': 2, 
         'long': 1, 
         'of': 2, 
         'short': 2, 
         'small': 1, 
         'words': 2}) 

请注意,计数器本身是使用 generator expression 构建的(又名 generator comprehension )。

另请注意,您甚至不需要创建字典。它是通过 Counter 为您创建的。

然后您可以使用字典理解来获取最常见的单词,例如前 5 名:

>>> {word: count for word, count in c.most_common(5)} 
{'big': 2, 'list': 2, 'of': 2, 'short': 2, 'words': 2}