0

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

1 Answer 1

2

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)]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.