python学习之Counter计数

可使用collection模块中的Counter函数对可迭代对象计数 from collections import Counter

l=list('shfajsdas') #将可迭代对象字符串转化为list
l
['s', 'h', 'f', 'a', 'j', 's', 'd', 'a', 's']
c=Counter(l) #利用Counter函数对列表计数
c #返回Counter对象
Counter({'s': 3, 'a': 2, 'd': 1, 'h': 1, 'j': 1, 'f': 1})
list(c) #获取无重复key组成的list
['d', 'h', 'a', 's', 'j', 'f']
c.elements()
<itertools.chain object at 0x1031486d8>
list(c.elements()) #获取所有的key
['d', 'h', 'a', 'a', 's', 's', 's', 'j', 'f']
c.most_common() #按照次数大小输出 列表嵌套元组
[('s', 3), ('a', 2), ('d', 1), ('h', 1), ('j', 1), ('f', 1)]
c.most_common(2) #输出出现最多次数的元素和出现次数 返回列表
[('s', 3), ('a', 2)]
sorted(c.most_common(),key=lambda x :x[0]) #排序 和字典排序类似
[('a', 2), ('d', 1), ('f', 1), ('h', 1), ('j', 1), ('s', 3)]

#这样是输出key 和字典类似 字典应该数d.items() 
sorted(c,key=lambda x :x[0])
['a', 'd', 'f', 'h', 'j', 's']

#字典
c={'a':3,'b':4}
list(c)
['b', 'a']
sorted(c,key=lambda x :x[0])
['a', 'b']
for i in c等价于for i in c.keys()
#应该是
sorted(c.items(),key=lambda x :x[0])

参考文档:

1.https://blog.csdn.net/u014755493/article/details/69812244

2.https://blog.csdn.net/fanlei5458/article/details/80147376

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值