2-3 如何统计序列中元素的出现频度
1.先将需要排序的放进列表中
2.使用Counter将列表转换成为字典
3.使用counter.max_common(N)方法列出top N
方法一, 通过正常的程序来解决,建立一个空字典,然后将序列中的元素作为key一个一个放进字典
lista = [1,2,3,3,2,2,2,5,6,1,2,2]
d = {}
for key in lista:
if key in d.iterkeys():
d[key] += 1
else:
d[key] = 1
print d
方法二,通过fromkeys 函数,由序列中所有的元素作为键,默认为0 建立一个字典
help(dict.fromkeys)
Help on built-in function fromkeys:
fromkeys(...)
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
lista = [1,2,3,3,2,2,2,5,6,1,2,2]
d2 = dict.fromkeys(lista,0)
for key in lista:
d2[key] += 1
print d2
方法三,使用collections下的Counter,将lista直接作为Counter的参数
1.先将需要排序的放进列表中
2.使用Counter将列表转换成为字典
3.使用counter.max_common(N)方法列出top N
import collections
lista = [1,2,3,3,2,2,2,5,6,1,2,2]
d3 = collections.Counter(lista)
print d3.most_common(4)
collections.Counter的帮助
help(collections.Counter)
Help on class Counter in module collections:
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.
|
| >>> c = Counter('abcdeabcdabcaba') # count elements from a string
|
| >>> c.most_common(3) # three most common elements
| [('a', 5), ('b', 4), ('c', 3)]
| >>> sorted(c) # list all unique elements
| ['a', 'b', 'c', 'd', 'e']
| >>> ''.join(sorted(c.elements())) # list elements with repetitions
| 'aaaaabbbbcccdde'