Nathan Tew
Nathan Tew

Reputation: 747

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.

Upvotes: 3

Views: 301

Answers (3)

Emmanuel Mtali
Emmanuel Mtali

Reputation: 4963

You might use:-

[item for sub_list in a[1:] for item in sub_list].count(1) # 3

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 3

miradulo
miradulo

Reputation: 29690

You could just use a generator and sum().

>>> a = [['a', 1], ['b', 1], [1, 1]]
>>> sum(ele[1] == 1 for ele in a)
3

Upvotes: 2

Related Questions