1.用内置的count()方法,该方法返回子字符串在字符串中出现的次数(同样适用于列表)
2.用collections模块的Counter类 示例:
 from collections import Counter

 # ================================================================================================== #
# 获取字符串string中a出现的次数
string = "abcdeabcabe" # 1. 用内置的count()方法
a1 = string.count('a') # # 2. 用collections模块的Counter类
# 实例化
c = Counter(string) # Counter对象 Counter({'a': 3, 'b': 3, 'c': 2, 'e': 2, 'd': 1})
# 将Counter对象转化成字典,其中元素是key,元素出现的频次为value
c_dict = dict(c) # {'a': 3, 'b': 3, 'c': 2, 'd': 1, 'e': 2}
# 获取a出现的次数
a2 = c_dict['a'] # # ================================================================================================== #
# 获取列表l中元素b出现的频次
l = ['a', 'b', 'a', 'c', 'b', 'a'] # 1. 用内置的count()方法
b1 = l.count('b') # # 2. 用collections模块的Counter类
# 实例化
c2 = Counter(l) # Counter对象 Counter({'a': 3, 'b': 2, 'c': 1})
# 将Counter对象转化成字典,其中元素是key,元素出现的频次为value
c_dict2 = dict(c2) # {'a': 3, 'b': 2, 'c': 1}
# 获取a出现的次数
b2 = c_dict2['b'] #
05-11 19:31