Home > Back-end >  Python: Sorting a Python list to show which string is most common to least common and the number of
Python: Sorting a Python list to show which string is most common to least common and the number of

Time:10-11

I have a winners list which will receive different entries each time the rest of my code is ran:

eg the list could look like:

winners = ['Tortoise','Tortoise','Hare']

I am able to find the most common entry by using:

mostWins = [word for word, word_count in Counter(winners).most_common(Animalnum)]   

which would ouput:

['Tortoise']

My problem is displaying the entire list from most common to least common and the how many times each string is found in the list.

CodePudding user response:

Just iterate over that .most_common:

>>> winners = ['Tortoise','Tortoise','Hare','Tortoise','Hare','Bob']
>>> import collections
>>> for name, wins in collections.Counter(winners).most_common():
...   print(name, wins)
...
Tortoise 3
Hare 2
Bob 1
>>>

CodePudding user response:

Counter is just a dictionary internally.

from collections import Counter
winners = ['Tortoise','Tortoise','Hare','Tortoise','Hare','Bob', 'Bob', 'John']
counts = Counter(winners)
print(counts)
# Counter({'Tortoise': 3, 'Hare': 2, 'Bob': 2, 'John': 1})
print(counts['Hare'])
# 2

Furthermore, the .most_common(n) method is just a .items() call on it that limits the output to n length. So you should only use it, if you'd like to show the top three, e.g.:

counts.most_common(3)
# [('Tortoise', 3), ('Hare', 2), ('Bob', 2)]
  • Related