【发布时间】: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