1. 程式人生 > >python技巧 計算字符串中字母出現的次數並取出最大

python技巧 計算字符串中字母出現的次數並取出最大

mon return 結果 現在 r12 for item python技巧 最大

有一個字符串 “aaddfdfdercfghfyttefsfsfewretr123trefg5624sdfcgvfdgte6435234532”,現在需要取出裏面出現次數最多的字符

第一種方法-裝飾器

class get_max_count_string:
def __init__(self,func):
self.func=func
self.count={}
def __call__(self, args):
for s in args:
if s in self.count:
self.count[s] +=1
else:
self.count[s] =1
key,value = max(self.count.items(),key=lambda x:x[1])
return key,value

@get_max_count_string
def filter_string(s):
return s

得到的結果是:

print(filter_string(‘aaddfdfdercfghfyttefsfsfewretr123trefg5624sdfcgvfdgte6435234532‘))
(‘2‘, 4)

第二種方法,使用python的collections.Counter

import collections

class get_max_count_string1:
def __init__(self,func):
self.func=func
def __call__(self, args):
s_count=collections.Counter(args)
return s_count.most_common(1)

@get_max_count_string1
def filter_string1(s):
return s

得到的結果

print(filter_string1(‘aaddfdfdercfghfyttefsfsfewretr123trefg5624sdfcgvfdgte6435234532‘))
[(‘f‘, 10)]
 

python技巧 計算字符串中字母出現的次數並取出最大