【问题标题】:How to print the most common element of a list?如何打印列表中最常见的元素?
【发布时间】:2018-02-25 00:13:05
【问题描述】:

在使用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

【问题讨论】:

  • 你使用的是 Python2 还是 Python3?
  • print 不是他代码中的函数,所以我假设 python2

标签: python list slice libraries


【解决方案1】:
    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'

【讨论】:

    【解决方案2】:

    使用 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() 并添加底线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2010-12-03
      • 2018-09-27
      相关资源
      最近更新 更多