如何打印列表中最常见的元素?

时间:2018-02-25 00:13:06

标签: python list slice libraries

在使用most_common函数后,我需要帮助查找如何将字符串中最常见的字母打印为字符。我的代码是:

from collections import*
message = input("What is the message you would like to decrypt?")
messageInt = list(map(ord,list(message)))
messageChr = list(map(chr,list(messageInt)))
print messageChr
fre = Counter(messageChr)
mostLett = fre.most_common(1)
print mostLett

如何打印:

['e', 'x', 'a', 'm', 'p', 'l', 'e']
[('e', 2)]
e

2 个答案:

答案 0 :(得分:2)

    l = ['e', 'x', 'a', 'm', 'p', 'l', 'e']

    Counter(l).most_common(1)[0][0]
    or 
    Counter(l).most_common(1).pop()[0]
    or
    mostCommonLetter, _ = Counter(l).most_common(1).pop()
    mostCommonLetter
    'e'

答案 1 :(得分:0)

使用Python 2,这是我假设你正在使用的,

from collections import*
message = raw_input("What is the message you would like to decrypt?")
messageInt = list(map(ord,list(message)))
messageChr = list(map(chr,list(messageInt)))
print messageChr
fre = Counter(messageChr)
mostLett = fre.most_common(1)
print mostLett
print mostLett[0][0]

input()替换为raw_input()并添加底线。