Home > Net >  How to get count of elements in a nested list?
How to get count of elements in a nested list?

Time:10-24

I am trying to count labels in a nested list and would appreciate any help on how to go about it. An example of the array I am trying to count is given below. This is not the real array, but a good enough approximation:

x = [[[0,0,1,0,2,3],-1],[[-1,1,1,0,2,5],-1],[[0,0,1,0,2,1],-1],[[0,0,-1,0,2,3],0]]

What I would like is to count all the occurrences of a given integer in the second element of the middle list (to visualize better, I would like to count all occurrences of X in the list like this [[[],X]]).

For instance, counting -1 in the above array would get 3 as a result and not 5. I do not want to get into loops and counters and such naive computations because the arrays I am working with are fairly large. Are there any standard python libraries that deal with such cases?

CodePudding user response:

One approach:

data = [[[0, 0, 1, 0, 2, 3], -1], [[-1, 1, 1, 0, 2, 5], -1], [[0, 0, 1, 0, 2, 1], -1], [[0, 0, -1, 0, 2, 3], 0]]


res = sum(1 for _, y in data if y == -1)
print(res)

Output

3

Alternative, use collections.Counter, if you need to count more than a single element.

res = Counter(y for _, y in data)
print(res)

Output

Counter({-1: 3, 0: 1})

A third alternative is use operator.countOf:

from operator import countOf
res = countOf((y for _, y in data), -1)
print(res)

Output

3

CodePudding user response:

You can use collections.Counter:

from collections import Counter
c = Counter((i[1] for i in x))
c[-1]

output:

>>> c[-1]
3

>>> c
Counter({-1: 3, 0: 1})
  • Related