I have the following task, there is a list of letters:

list = "AaaBbBCcDdddGggPpjjJ" 

I need to count the number of letters in the list and display the letters - which appears in the list the maximum number of times.

The decision with counting letters, I see the following:

 list = ( ", ".join("%s : %s" % (i, a.count(i)) for i in sorted(set(a.lower())))).split(',') print(list) 

It turns out the following list:

 ['a : 2', ' b : 1', ' c : 1', ' d : 3', ' g : 2', ' j : 2', ' p : 1'] 

Now, the task is to remove from this list the most frequently used letter. It seems to me that if I convert this list to a dictionary, then by the maximum value I can get the desired result.

 {a:2}, {b:1}, {c:1} и т.д. 

But bad luck, I can not figure out how to do it?

  • In python, there is no character type, so the string is not a list of characters . In many respects it is similar, but the string and the list are different types. - andy.37
  • @ andy.37 in programming, the word "character" is often used to denote a line element (text element). More precisely, it would be necessary to say that a string is a sequence of characters (since the word "list" with the built-in type list can cause confusion). But informally, you can use the word list (as a synonym for "sequence"). In general, a symbol can be a byte, and a code unit, and a code point, and grapheme cluster, and glyph, and anything else, depending on the environment and the task). Example: How to break a string into separate characters? - jfs
  • @jfs I understand all this. It's just that in the python (but not only in it) the string is a rather “special” sequence. And even iterating over a string (funny word) for symbol in "abcd": at each step we will receive exactly the string that just consists of one symbol (unlike most other languages). And the properties of the string "abc" quite different from the properties of the list (sequence) of "characters" ['a', 'b', 'c'] - andy.37

2 answers 2

The collections package has everything you need for this task =)

 import collections s = "AaaBbBCcDdddGggPpjjJ" #если регистрозависимая разница, иначе к list применить метод lower() print(collections.Counter(s).most_common(1)[0]) 

As already mentioned, Counter great option, but it can be done with a simple generator:

 In [30]: _str = 'aaaaaaaaaaaavcdffffffffffffffffffffffffffff' In [31]: result = {key : _str.count(key) for key in set(_str)} In [32]: sorted(result.items(), key = lambda item: item[1])[-1] Out[32]: ('f', 28)