python 2-3 如何统计序列中元素的出现频度--collections.Counter

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'
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值