Accessing counts associated to each elements [duplicate]


Accessing counts associated to each elements [duplicate]



This question already has an answer here:



If a have a list of elements with theirs counts as below


[('a', 1), ('b', 2), ('c', 2),('d', 3), ('e', 3)]



And now I want to find out how many of them appear once,twice,and three times.
So the expected output would be something like


1:1,2:2,3:2



The list is generated by the Counter function Counter(lst)


Counter


Counter(lst)



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




2 Answers
2



Use another Counter on the values of your first Counter.


Counter


values


Counter


from collections import Counter

s = 'abbccdddeee'
c = Counter(s)
counts = Counter(c.values())



Use collections.Counter again but this time count second element in each tuple.


collections.Counter


from collections import Counter

lst = [('a', 1), ('b', 2), ('c', 2),('d', 3), ('e', 3)]

print(Counter(x[1] for x in lst)) # x[1] takes second element from each tuple.
# Counter({2: 2, 3: 2, 1: 1})

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?