1

给定一个像“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”

4

2 回答 2

8

像这样:max()使用str.split()

>>> strs= "abbbd cdda cbaa"
>>> max(strs.split(),key=lambda x:x.count("b"))
'abbbd'
于 2012-10-24T10:31:06.017 回答
0

collections库包含有用的类,该类Counter也可用于计算集合中最常见的元素。

>>> import collections
>>> sample = "abbbd cdda cbaa"
>>> collections.Counter(sample).most_common(1)
[('a', 4)]

请注意,参数指定要返回的元素的数量(从最常见到最不常见)——在这种情况下,只需要最常见的元素。

于 2020-06-03T09:43:30.907 回答