问题要求我返回一个小写字符串,其中包含按字母顺序排列的 s 中最常出现的字母。到目前为止我已经:
def mostFrequentLetter(s):
allchar = ''.join(sorted(s))
temp = s.replace(" ","")
max = None
maxchar = None
for alph in allchar.lower():
charcount = temp.count(alph)
if alph not in string.ascii_letters: continue
elif charcount > max:
max = charcount
max = alph
elif charcount == max:
max2 = charcount
max2 = alph
max.append(max2)
return max
如果我输入'aaaabbbb'
,它应该给我'ab'
,但它只给我'a'
。我该如何解决这个问题?
最佳答案
您可以使用内置 collections.Counter :
from collections import Counter
def most_frequent_letter(s):
counter = Counter(s)
letter, max_count = next(counter.most_common())
letters = sorted(letter
for letter, count in counter.most_common()
if count == max_count)
return ''.join(letters)
如果由于某种原因您无法使用Counter
,您可以使用default dictionary :
from collections import defaultdict
def most_frequent_letter(s):
counter = defaultdict(int)
for char in s:
counter[char] += 1
max_count = max(counter.values())
letters = sorted(letter
for letter, count in counter.items()
if count == max_count)
return ''.join(letters)
关于python - python 字符串中出现频率最高的一个或多个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329411/