Python中的count函数和Counter函数

文章目录

    • str.count()
    • list.count()
    • Counter()

str.count()

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

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

参数

  • sub —— 需要搜索的子字符串
  • start —— 字符串开始搜索的位置,默认为第一个字符(索引值0)
  • end —— 字符串结束搜索的位置,默认为最后一个字符(默认值为字符串长度)。字符串搜索只到end位置前一个字符,搜索不包括索引值为end值的字符
1
2
3
4
5
6
7
8
9
10
11
12
13
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()方法用来统计列表中某个元素出现的次数。

1
list.count(obj)

参数

  • obj —— 列表中需要统计的对象
1
2
3
4
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个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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用法的官方文档