1

I want to access or select the first number in counter using Python. So I have this code, that will run random number from 1 to 10 with 100 trials, then it will count the most frequent number that occured.

from collections import Counter
from random import choice

y = []
for x in [(choice([i for i in range(1,10) if i not in [0]])) for j in range(100)]:
    y.append(x)
a = Counter(y)
b= a.most_common(1)
print(b)

I want to know that number so I need to select it alone. So for example, my output is

[(2, 17)]

2 is the most frequent number, so how I'm going to select that number from that structure type. Expected output:

2

Thanks for the help!

Chandan
  • 571
  • 4
  • 21
nobel
  • 51
  • 1
  • 8

2 Answers2

2

If you want only the top most common, the preferred way is:

a = collections.Counter(y)
most_common = max(a, key=a.get)
print(most_common)

Output

2

The reason for doing that instead of using most_common, is specified in the documentation of heap (the inner data structure used by Counter):

The latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

You can also do:

b= a.most_common(1)[0][0]
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58