找到一个单词中最常见的字母;按字母顺序

时间:2017-12-16 12:23:06

标签: python python-3.x dictionary

程序输入是一个字符串。从这个字符串我想要最常见的字母。如果有多个字母具有相同的频率,我将返回拉丁字母中首先出现的字母

代码:

def most_Wanted(text="Hello Oman"):
    lst = [x for x in text.replace(" ","").lower() if x.isalpha]
    count = {}
    for letter in lst:
        if letter in count:
            count[letter] += 1
        else:
            count[letter] = 1
    count = list(count.items())
    sorted(count, key=lambda x: (-x[1],x[0]))
    print(count[0][0])

预期:

l #though o and l appear 3 times, l is before o in the latin alphabet

输出:

h #there seems to be an error in the sorting as the first pair of tuples in the list always seems to be the first letter of the text?

任何修改代码的建议都没问题,但我现在不想使用模块,所以我可以学习核心python。谢谢:))

1 个答案:

答案 0 :(得分:3)

主要问题是sorted返回一个新列表,它不在原地。

您应该重新分配其返回值,或使用.sort()

count = sorted(count, key=lambda x: (-x[1],x[0]))

count.sort(key=lambda x: (-x[1],x[0]))


该行还有一个问题

lst = [x for x in text.replace(" ","").lower() if x.isalpha]

if x.isalpha始终返回True,因为它只引用该函数而不是实际调用它。它应该改为

lst = [x for x in text.replace(" ","").lower() if x.isalpha()]