Count items in list and make it a dictionary
本问题已经有最佳答案,请猛点这里访问。
我正试图从列表中生成词典
1 | names = ['tango', 'bravo', 'tango', 'alpha', 'alpha'] |
结果应该是这样的:
1 | {'tango': 2 , 'bravo': 1 , 'alpha': 2} |
号
我怎样才能做到?
这正是
1 2 3 | >>> from collections import Counter >>> Counter(['tango', 'bravo', 'tango', 'alpha', 'alpha']) Counter({'tango': 2, 'alpha': 2, 'bravo': 1}) |
您可以像使用字典一样使用
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} |
号