python之Counter,items,sorted,count

本文介绍Counter、items和sorted使用。

1 Counter

作用:统计字符出现的次数。

  • Demo
from collecitons import Counter
voc = 'hellothankyou'
voc1 = ['a','b','c','a','b','b']

counter = collections.Counter(voc)
counter1 = collections.Counter(voc1)

print(counter)
print(counter1)
  • Result
Counter({'h': 2, 'l': 2, 'o': 2, 'e': 1, 't': 1, 'a': 1, 'n': 1, 'k': 1, 'y': 1, 'u': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

2 items

作用:列表形式返回可遍历的值。

  • Demo
voc2 = {'name':'xin','sex':'male','job':'AI'}
output = voc2.items()
print(type(output))
print(output)
for k,v in output:
	print(k,v)
  • Result
<class 'dict_items'>
dict_items([('name', 'xin'), ('sex', 'male'), ('job', 'AI')])
name xin
sex male
job AI

3 sorted

作用:对所有可迭代的对象进行排序。
sorted(iterable[,cmp[,key[,reverse]]])
(1)iterable:可迭代对象
(2)cmp:比较的函数,有两个参数,参数的值都是从可迭代的对象中取出,大于则返回1,小于返回-1,等于返回0
(3)key:用于进行比较的元素
(4)reverse:排序规则,reverse=True降序,reverse=False升序(默认)

  • Demo
voc = 'hellothankyou'
voc2 = [('a',3),('b',2),('c',1)]
output1 = sorted(voc)
#按第一个元素进行排序
output2 = sorted(voc2, key=lambda x:x[0])
#按第二个元素排序
output3 = sorted(voc2, key=lambda x:x[1])
print(output1)
print(output2)
print(output3)
  • Result
['a', 'e', 'h', 'h', 'k', 'l', 'l', 'n', 'o', 'o', 't', 'u', 'y']
[('a', 3), ('b', 2), ('c', 1)]
[('c', 1), ('b', 2), ('a', 3)]

4 count

统计列表中变量出现的次数。

  • Demo
a = ['abc', 'abc', 'def']
print("Count of a's value: {}".format(a.count('abc')))
  • Result
Count of a's value: 2

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值