0

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?

2
  • 1
    Please provide enough code so others can better understand or reproduce the problem. Commented Oct 23, 2021 at 15:25
  • please provide code Commented Oct 23, 2021 at 15:26

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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]

        ]

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.