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)]
 
posted @ 2018-12-10 19:34  丁壮  阅读(2620)  评论(0编辑  收藏  举报