Python中的count函数和Counter函数

str.count()

str.count()方法用来统计字符串里某个字符出现的次数。

str.count(sub,start=0,end=len(string))

参数

  • sub —— 需要搜索的子字符串
  • start —— 字符串开始搜索的位置,默认为第一个字符(索引值0)
  • end —— 字符串结束搜索的位置,默认为最后一个字符(默认值为字符串长度)。字符串搜索只到end位置前一个字符,搜索不包括索引值为end值的字符
Str = "Tomorrow will be another day.The sun also rise"
print("len(Str):",len(Str))

sub1 = ' '
print("str.count(' '):",Str.count(sub1))    # 统计字符串中空格出现的次数

sub2 = 'th'
print("str.count('th'):",Str.count(sub2))   # 统计字符串中'th'出现的次数

sub3 = 'e'
print("str.count('e'):",Str.count(sub3))   # 统计字符串中'e'出现的次数
print("str.count('e',start=15,end=46):",Str.count(sub3,16,46))   # 统计从第5到最后一个字符,'e'出现的次数
print("str.count('e',start=15,end=45):",Str.count(sub3,16,45))

输出结果:
len(Str):46
str.count(’ '):7
str.count(‘th’):1
str.count(‘e’):4
str.count(‘e’,start=15,end=46):3
str.count(‘e’,start=15,end=45):2

list.count()

list.count()方法用来统计列表中某个元素出现的次数。

list.count(obj)

参数

  • obj —— 列表中需要统计的对象
List = ['appel','pear','orange','banana','pear','mango','grape']

print("列表中'pear'出现的次数:",List.count('pear'))
print("列表中'watermelon'出现的次数:",List.count('watermelon'))

输出结果:
列表中’pear’出现的次数: 2
列表中’watermelon’出现的次数: 0

Counter()

Counter()也可以用于统计字符出现的个数或列表中元素出现的次数。返回结果按出现次数从多至少排列。
一个Counter是一个dict的子类,用于计数可哈希对象。

Counter().most_common(n)返回数组中出现次数最多的元素。参数n表示的含义是:输出出现次数最多的前n个元素。

from collections import Counter

List = ['appel','pear','orange','banana','pear','mango','grape']
a = Counter(List)
print(a)

b = Counter("It's fine today.") 	# 空格以及符号出现次数也会统计
print(b)

b.update(List)  # 添加
print(b)

c = b.most_common(3)
print('出现次数前三的元素:',c)

输出结果:
Counter({‘pear’: 2, ‘appel’: 1, ‘orange’: 1, ‘banana’: 1, ‘mango’: 1, ‘grape’: 1})
Counter({‘t’: 2, ’ ‘: 2, ‘I’: 1, "’": 1, ‘s’: 1, ‘f’: 1, ‘i’: 1, ‘n’: 1, ‘e’: 1, ‘o’: 1, ‘d’: 1, ‘a’: 1, ‘y’: 1, ‘.’: 1})
Counter({‘t’: 2, ’ ‘: 2, ‘pear’: 2, ‘I’: 1, "’": 1, ‘s’: 1, ‘f’: 1, ‘i’: 1, ‘n’: 1, ‘e’: 1, ‘o’: 1, ‘d’: 1, ‘a’: 1, ‘y’: 1, ‘.’: 1, ‘appel’: 1, ‘orange’: 1, ‘banana’: 1, ‘mango’: 1, ‘grape’: 1})
出现次数前三的元素: [(‘t’, 2), (’ ', 2), (‘pear’, 2)]

点击此处,更多Counter的用法
关于Counter用法的官方文档

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值