函数介绍:
(推荐教程:Python入门教程)
count()函数
Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。该方法返回子字符串在字符串中出现的次数。
函数语法:
str.count(sub, start= 0,end=len(string))
参数说明:
sub -- 搜索的子字符串
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
代码实现:
# 方法一 List =[1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] Strlist=['A','B','B','C','C','C','D','D','D','D'] a=set(List) b=set(Strlist) print(List) print(Strlist) print(a) for i in a: count =List.count(i) print(i,'出现的次数:',count) for i in b: count =Strlist.count(i) print(i,'出现的次数:',count) print('-'*20) #方法二 List =[1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] Strlist=['A','B','B','C','C','C','D','D','D','D'] d1 = {} d2 = {} for i in List: if List.count(i) >= 1: d1[i] = List.count(i) print(d1) for i in Strlist: if Strlist.count(i) >= 1: d2[i] = Strlist.count(i) print(d2) print('-'*20) #方法三 from collections import Counter List =[1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] Strlist=['A','B','B','C','C','C','D','D','D','D'] res = Counter(List) print(res) res=Counter(Strlist) print(res)