关于python:计算列表中的项目并使其成为字典

Count items in list and make it a dictionary

本问题已经有最佳答案,请猛点这里访问。

我正试图从列表中生成词典

1
names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']

结果应该是这样的:

1
{'tango': 2 , 'bravo': 1 , 'alpha': 2}

我怎样才能做到?


这正是Counter的作用。

1
2
3
>>> from collections import Counter
>>> Counter(['tango', 'bravo', 'tango', 'alpha', 'alpha'])
Counter({'tango': 2, 'alpha': 2, 'bravo': 1})

您可以像使用字典一样使用Counter对象,因为它是内置dict的子类。文件摘录:

class Counter(__builtin__.dict)
Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.

编辑:

按照要求,这里有另一种方法:

1
2
3
4
5
6
7
>>> names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']
>>> d = {}
>>> for name in names:
...     d[name] = d.get(name, 0) + 1
...
>>> d
{'bravo': 1, 'tango': 2, 'alpha': 2}