如何生成每个元素到其出现次数的映射?

时间:2015-04-22 01:19:28

标签: python python-2.7

我有一个定义的列表为list =["a","b","d","f","g","a","g","d","a","d"],我想要一个像这样dicc = {a:2, b:1, d:3, f:1, g:2}的字典。此字典中的值是列表元素在列表中重复的次数。我尝试了下面但我不知道在#中放什么。

dicc = dict(zip(list,[# for x in range(#c.,len(list))]))


lista = ["a","b","d","f","g","a","g","d","a","d"]
dicc = dict(zip(list,[# for x in range(#c.,len(list))]))
print dicc 
dicc = {a:2, b:1, d:3, f:1, g:2}

1 个答案:

答案 0 :(得分:3)

这正是Counter类的作用。

from collections import Counter
Counter(lista)
=> Counter({'d': 3, 'a': 3, 'g': 2, 'b': 1, 'f': 1})

Counterdict的子类,因此您可以将其用作词典。