给定一个字符串,例如“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"
请您参考如下方法:
像这样:将 max() 与 str.split() 一起使用:
>>> strs= "abbbd cdda cbaa"
>>> max(strs.split(),key=lambda x:x.count("b"))
'abbbd'
