Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count occurrences of a specific element in a position in a list of lists?

For example,

a=[[a, 1], [b, 1], [1, 1]]

I want to find how many "1"s there are, but only those that are the second element in the nested lists. So it should give me 3, ignoring the "1" in the third list as it is the first element in the list.

like image 962
Nathan Tew Avatar asked Feb 02 '26 01:02

Nathan Tew


1 Answers

Use collections.Counter subclass to count occurrences of any value:

import collections

a = [['a', 1], ['b', 1], [1, 1]]
counts = collections.Counter((l[1] for l in a))

print(counts[1])   # 3
like image 99
RomanPerekhrest Avatar answered Feb 03 '26 13:02

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!