返回特定ch出现次数最高的字符串

2024-09-27 21:33:20 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个类似“abbbd cdda cbaa”的字符串,您将如何确定“b”等特定字符出现率最高的单词。我的初始代码:

sample = "abbbd cdda cbaa"
sample_splitter = sample.split()
#sample_splitter is now [abbbd, cdda, cbaa]
for word in sample_splitter:
  word.count("b") #this returns the number of occurrences of the char b
  max(word.count("b")) #this will return the highest number

我一直在想如何将字母的最高计数与与之关联的数组值相关联。在这种情况下,应该是“abbbd”


Tags: ofthesample字符串代码numbercountthis
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:20

如下所示:将max()str.split()一起使用:

>>> strs= "abbbd cdda cbaa"
>>> max(strs.split(),key=lambda x:x.count("b"))
'abbbd'

相关问题 更多 >

    热门问题