Python 查找字符串中出现次数最多的字母,只打印字母,而不打印计数

Python 查找字符串中出现次数最多的字母,只打印字母,而不打印计数,python,Python,如何从字符串中找到外观最多的字母,并只输出字母,而不输出计数? 对于collections.Counter,它总是显示计数和字母。电流输出:“l”,3。首选输出:l import collections s = "helloworld" print(collections.Counter(s).most_common(1)[0]) 而不是 print(collections.Counter(s).most_common(1)[0]) 你可以写 print(collect

如何从字符串中找到外观最多的字母,并只输出字母,而不输出计数? 对于collections.Counter,它总是显示计数和字母。电流输出:“l”,3。首选输出:l

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

而不是

print(collections.Counter(s).most_common(1)[0])
你可以写

print(collections.Counter(s).most_common(1)[0][0])

它将为您提供元组的第一个元素,因此输出为l。

您还可以执行以下操作:

txt = "aaaaaaaabbbbbcccdde"
print(max(set(txt), key=txt.count))
输出:

a
您可以将max函数与另一个函数一起用作关键参数,如下所示:

s=地狱世界 printmaxs,key=lambda c:s.countc 关键参数是一个函数,用于比较iterable的两个项目。在这种情况下,我们根据每个项目的出现情况进行比较