如何计算唯一标签的出现次数?

min*_*nks 1 python

我有一个包含如下标签的文档:

201
202
205
201
203
204
201
Run Code Online (Sandbox Code Playgroud)

如果我想计算每个标签出现的次数并将其打印出来,我该如何在Python中做到这一点?

我想要得到的是:

201: 3
202: 1
204: 1 
Run Code Online (Sandbox Code Playgroud)

Iro*_*ist 5

使用Counterfromcollections模块将键映射为字符串及其计数

>>> from collections import Counter
>>> 
>>> s
'202\n205\n201\n203\n204\n201\n'
>>> s = '''
201
202
205
201
203
204
201
'''
>>> c=Counter()
>>> for d in s.rstrip().split():
        c[d] += 1


>>> c
Counter({'201': 3, '205': 1, '204': 1, '203': 1, '202': 1})
Run Code Online (Sandbox Code Playgroud)

或者按照Kevinguan的建议:

>>> c = Counter(s.rstrip().split())
Run Code Online (Sandbox Code Playgroud)

编辑:

我认为这可以进一步简单地完成,这样:

>>> l = s.rstrip().split()
>>> l
['201', '202', '205', '201', '203', '204', '201']
>>> c = [l.count(x) for x in l]
>>> 
>>> c
[1, 1, 1, 3, 1]
>>> 
>>> d = dict(zip(l,c))
>>> 
>>> d
{'205': 1, '201': 3, '203': 1, '204': 1, '202': 1}
Run Code Online (Sandbox Code Playgroud)

如果您对一种线性表达感兴趣,那么:

>>> l = s.rstrip().split()
>>>
>>> dict(zip(l,map(l.count, l)))
{'205': 1, '204': 1, '201': 3, '203': 1, '202': 1}
>>>
>>> dict(zip(set(l),map(l.count, set(l))))
{'205': 1, '201': 3, '203': 1, '204': 1, '202': 1}
Run Code Online (Sandbox Code Playgroud)