Counting a certain no in list in while loop

Question:

I’ve this variable a as:

a = [(1,10),(2,20),(3,30),(4,10),(6,10),(7,20),(8,30)]

here in the variable (1,10),1 is the id and 10 is status.
i’ve to check how many time a single status is coming and get the top3,

10 = 3 20 = 2 30 = 2

x = 0 while (x< len(a)): print(a[x][1]) x+=1

I’m getting it like this but i don’t how to count them while in a loop, so please help me out on this

10
20
30
10
10
20

Asked By: code_wizard3199

||

Answers:

Use collections.Counter.

import collections

a = [(1, 10), (2, 20), (3, 30), (4, 10), (6, 10), (7, 20), (8, 30)]

print(collections.Counter(x[1] for x in a))

This will give you Counter({10: 3, 20: 2, 30: 2}).


If you want to limit the results then use most_common.

c = collections.Counter(x[1] for x in a)
print(c.most_common(2))

[(10, 3), (20, 2)]

Answered By: Matthias
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.