欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python技巧 计算字符串中字母出现的次数并取出最大

程序员文章站 2022-07-02 17:29:27
有一个字符串 “aaddfdfdercfghfyttefsfsfewretr123trefg5624sdfcgvfdgte6435234532”,现在需要取出里面出现次数最多的字符 第一种方法-装饰器 得到的结果是: 第二种方法,使用python的collections.Counter 得到的结果 ......

有一个字符串 “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)]