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

问题描述 投票:2回答:1

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

码:

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。谢谢:)

python python-3.x dictionary
1个回答
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()]
© www.soinside.com 2019 - 2024. All rights reserved.