This question already has answers here:
How can I count the occurrences of a list item?
                                
                                    (22个答案)
                                
                        
                                3年前关闭。
            
                    
我有一个包含如下标签的文档:

201
202
205
201
203
204
201


如果我想计算每个标签的出现次数并打印出来,如何在python中这样做?

我想要得到的是:

201: 3
202: 1
204: 1

最佳答案

尝试这个:

import itertools

with open("your_document") as f:
    lines = sorted(map(str.int, f.read().strip().split()))
    for x,y in itertools.groupby(lines):
        print x, list(y)


如果您的文档非常庞大,例如Gb

import collections
my_dict = collections.defaultdict(int)
with open("your_document") as f:
    for line in f:
        my_dict[line] += 1


输出:

>>> my_dict
defaultdict(<type 'int'>, {'201': 2, '203': 1, '202': 1, '205': 1, '204': 1})


没有集合或itertools:

my_dict = {}
with open("your_document") as f:
    for line in f:
        line = line.strip()
        my_dict[line] = my_dict.get(line, 0) + 1

10-07 19:11