有一个字符串 “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)]
继续阅读与本文标签相同的文章
上一篇 :
浅谈CPU 并行编程和 GPU 并行编程的区别
下一篇 :
多措并举推进机器人产业发展
-
DBengine 排名第一,云数据库 InfluxDB 版正式商业化!
2026-05-19栏目: 教程
-
阿里有个超神秘的组织,CEO们来了都要翻牌 | 开发者必读(056期)
2026-05-19栏目: 教程
-
云原生计算重塑企业IT架构 - 分布式应用架构
2026-05-19栏目: 教程
-
阿里云创新大会再出发,一些变化即将发生
2026-05-19栏目: 教程
-
阿里云的包年包月、按量付费、抢占式实例计费方式是什么,如何选择
2026-05-19栏目: 教程
