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)]
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM