silal anwar
silal anwar

Reputation: 1

How to get count of elements in a nested list?

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?

Upvotes: 0

Views: 432

Answers (3)

PythonProgrammi
PythonProgrammi

Reputation: 23443

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]

        ]

These are the items of the list [ [....], x] with another list and an integer. You want to count how many times the x is -1 and not 0.

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]

        ]

def counter(_list, element):
    count = 0
    for item in _list:
        if item[1] == element:
            count += 1
    return count

print(counter(x, -1))

>>> 3

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 1

mozway
mozway

Reputation: 260600

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

Upvotes: 0

Related Questions