【问题标题】:Manipulating counter information - Python 2.7操作计数器信息 - Python 2.7
【发布时间】:2013-11-19 23:29:33
【问题描述】:

我对 Python 还很陌生,我正在修改这个程序。它应该从输入中获取一个字符串并显示哪个字符最频繁。

stringToData = raw_input("Please enter your string: ")
    # imports collections class
import collections
    # gets the data needed from the collection
letter, count = collections.Counter(stringToData).most_common(1)[0]
    # prints the results
print "The most frequent character is %s, which occurred %d times." % (
letter, count)

但是,如果字符串中每个字符都有 1,则它只显示一个字母并表示它是最常见的字符。我想过在 most_common(number) 中更改括号中的数字,但我不想更多地显示其他字母每次显示多少次。

感谢大家的帮助!

【问题讨论】:

  • 您可以将参数留给most_common 以获取所有字符的列表,按最常见到最不常见的顺序排列。然后只需遍历该结果并收集字符,只要计数器值仍然相同。这样你就可以得到所有最常见的字符。
  • 所以去掉 most_common 上的 (1)?我现在如何使用 most_common() 访问该列表?

标签: python collections counter


【解决方案1】:

正如我在评论中解释的那样:

您可以将参数保留为most_common,以获取所有字符的列表,按最常见到最不常见的顺序排列。然后只需遍历该结果并收集字符,只要计数器值仍然相同。这样您就可以获得所有最常见的字符。

Counter.most_common(n) 从计数器返回n 最常见的元素。或者如果没有指定n,它将返回计数器中的所有元素,按计数排序。

>>> collections.Counter('abcdab').most_common()
[('a', 2), ('b', 2), ('c', 1), ('d', 1)]

您可以使用此行为简单地遍历所有元素,按其数量排序。只要计数与输出中第一个元素的计数相同,您就知道该元素在字符串中仍然以相同的数量出现。

>>> c = collections.Counter('abcdefgabc')
>>> maxCount = c.most_common(1)[0][1]

>>> elements = []
>>> for element, count in c.most_common():
        if count != maxCount:
            break
        elements.append(element)
>>> elements
['a', 'c', 'b']

>>> [e for e, c in c.most_common() if c == maxCount]
['a', 'c', 'b']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多