sally = "sally sells sea shells by the sea shore"
characters = {}
for i in sally:
if i not in characters:
characters[i] = 0
characters[i] += 1
best_char = max(characters.keys()) max函数将'y‘显示为最频繁的字母,而不是's’。我从堆栈和极客那里找到了一些极客的方法,但作为初学者,它们要么不必要地冗长,要么对我来说很复杂。谢谢。对于任何错误/不便,我深表歉意。
发布于 2020-06-25 20:13:26
我发现你的代码有两个问题:
maximum letter根据字母数字分类应该是'y‘,而您希望看到出现次数最多的字母,因此您应该改为按值排名。我在下面的代码中保持了您的方法的精神,但是您应该知道,在python中,您有更高效/更优雅的解决方案来实现您正在尝试实现的目标。
import operator
sally = "sally sells sea shells by the sea shore"
characters = {}
for i in sally:
if i not in characters:
characters[i] = 0
characters[i] += 1
best_char = max(characters.values())
best_char = max(characters.items(), key=operator.itemgetter(1))[0]发布于 2020-06-25 20:13:54
在您的代码中,您使用了最大的dict键,而不是它们的数量。也许您想要这样的内容,它将返回"s":
sally = "sally sells sea shells by the sea shore"
characters = {}
for i in sally:
if i not in characters:
characters[i] = 0
characters[i] += 1
counts = sorted([ (k,v) for k,v in characters.items() ], key=lambda x: x[1])
best_char = counts[-1][0] # s发布于 2020-06-25 20:14:50
此输出是预期的,因为您采用键的最大值。键是由ASCII值表示的字符,因为'y‘是您输入的字母表中的最新字母,所以它具有最大值。在ASCII中a= 97,z= 122。
获取具有最大值作为其值的键的一种方法是:
key_with_max_value = max(characters, key=characters.get)
print(key_with_max_value)Python字典方法get()为给定的键返回一个值。
https://stackoverflow.com/questions/62574885
复制相似问题