1

I have a list of names, some names may be iterated. I want to make a counter for each name to select the maximum iterated one. For example my list is as follow:

list = ['ABC', 'BCD', 'ASD', 'ABC', 'ABC', 'ABC', 'ZXC', 'BCD']

I want the program to return:

ABC = 4
BCD = 2
ASD = 1
ZXC = 1

Finally I want to select the maximum iterated name as a winner. How can I do that. Can anyone please help me, I will be thankful to him.

hh tt
  • 395
  • 5
  • 22
  • I added one more duplicate @CoryKramer because I wanted to make sure using `Counter.most_common` was front and center in one the answers. – Christian Dean Mar 13 '19 at 15:08

1 Answers1

3

You can use collections.Counter:

from collections import Counter
Counter({'ABC': 4, 'BCD': 2, 'ASD': 1, 'ZXC': 1})
# Counter({'ABC': 4, 'BCD': 2, 'ASD': 1, 'ZXC': 1})

And in order to obtain string with the highest amount of counts you can use the most_common method from the Counter:

Counter(l).most_common(1)
# [('ABC', 4)]
yatu
  • 86,083
  • 12
  • 84
  • 139