从列表中创建字典,其中列表项成为键,值成为它们在列表中的次数。
aabb5888157 回答:如何从列表返回字典,其中关键字是列表中的项,值是python中该列表中出现的次数?
d = {}
for items in your_list:
d[items] = your_list.count(items)
,
计数器将一系列值转换为类似defaultdict(int)的对象,将键映射到计数。
from collections import Counter
c = Counter([0,1,2,0]) # c is (basically) { 0 : 2,1 : 1,2 : 1 }
一种有用的Counter方法是most_common
。
# print the 10 most common words and their counts in the Counter Dict on myList:
for word,count in Counter(myList).most_common(10):
print(word,count)