1.用內置的count()方法,該方法返回子字符串在字符串中出現的次數(同樣適用於列表)
2.用collections模塊的Counter類
示例:
1 from collections import Counter 2 3 # ================================================================================================== # 4 # 獲取字符串string中a出現的次數 5 string = "abcdeabcabe" 6 7 # 1. 用內置的count()方法 8 a1 = string.count('a') # 3 9 10 # 2. 用collections模塊的Counter類 11 # 實例化 12 c = Counter(string) # Counter對象 Counter({'a': 3, 'b': 3, 'c': 2, 'e': 2, 'd': 1}) 13 # 將Counter對象轉化成字典,其中元素是key,元素出現的頻次為value 14 c_dict = dict(c) # {'a': 3, 'b': 3, 'c': 2, 'd': 1, 'e': 2} 15 # 獲取a出現的次數 16 a2 = c_dict['a'] # 3 17 18 # ================================================================================================== # 19 # 獲取列表l中元素b出現的頻次 20 l = ['a', 'b', 'a', 'c', 'b', 'a'] 21 22 # 1. 用內置的count()方法 23 b1 = l.count('b') # 2 24 25 # 2. 用collections模塊的Counter類 26 # 實例化 27 c2 = Counter(l) # Counter對象 Counter({'a': 3, 'b': 2, 'c': 1}) 28 # 將Counter對象轉化成字典,其中元素是key,元素出現的頻次為value 29 c_dict2 = dict(c2) # {'a': 3, 'b': 2, 'c': 1} 30 # 獲取a出現的次數 31 b2 = c_dict2['b'] # 2