简体   繁体   中英

How to print the most common element of a list?

I need help finding how to print the most common letter of a string as a character after using the most_common function is used. My code is:

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

How do I get it to print:

['e', 'x', 'a', 'm', 'p', 'l', 'e']
[('e', 2)]
e
    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'

With Python 2, which is what I assume you're using,

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]

replace input() with raw_input() and add the bottom line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM