给定输入为“句子”,如何返回最多出现的元素

时间:2017-03-14 19:46:55

标签: python python-3.x

第一个函数计算字符串的字符

def character_count(sentence):
    characters = {}
    for char in sentence:
        if char in characters:
            characters[char] = characters[char] + 1
        else: 
            characters[char] = 1
    return characters

第二个函数确定最常见的字符,并通过在前一个辅助函数中建立的字符[char]来识别哪个字符最常出现

def most_common_character(sentence):
    chars = character_count(sentence)
    most_common = ""
    max_times = 0


    for curr_char in chars:
        if chars[curr_char] > max_times:
            most_common = curr_char
            max_times = chars[curr_char]
    return most_common

2 个答案:

答案 0 :(得分:2)

为什么不简单地使用Python提供的内容?

>>> from collections import Counter
>>> sentence = "This is such a beautiful day, isn't it"
>>> c = Counter(sentence).most_common(3)
>>> c
[(' ', 7), ('i', 5), ('s', 4)]

如果你真的想逐字逐句地避开空格:

>>> from collections import Counter
>>> sentence = "This is such a beautiful day, isn't it"
>>> res = Counter(sentence.replace(' ', ''))
>>> res.most_common(1)
[('i', 5)]

答案 1 :(得分:1)

你实际上不需要改变任何东西!您的代码将按原样使用列表(变量名称只会变得误导)。试试吧:

most_common_character(['this', 'is', 'a', 'a', 'list'])

输出:

'a'

这适用于包含任何可清洗元素(数字,字符串,字符等)的列表