Avan Wansing
Avan Wansing

Reputation: 261

Count number of occurrence in the list

I have a list like this:

res = [[('CARDINAL', 1)], [('CARDINAL', 4)], [('CARDINAL', 1), ('ORG', 1)],
       [('CARDINAL', 1)], [('ORG', 1)], [('OTHER', 1)], [('CARDINAL', 1)]]

how can I get output like

[{'CARDINAL' : 8, 'ORG' : 2, 'OTHER' : 1}]

Upvotes: 0

Views: 68

Answers (2)

blhsing
blhsing

Reputation: 106455

You can convert the sequences of tuples to dicts first to construct Counter objects with the dicts so that you can take advantage of Counter's key-based addition operation using the sum function:

from collections import Counter
sum(map(Counter, map(dict, res)), Counter())

which returns:

Counter({'CARDINAL': 8, 'ORG': 2, 'OTHER': 1})

Alternatively, use the reduce function with the add operator function to achieve the same result without having to initialize an empty Counter as a starting value:

from collections import Counter
from functools import reduce
from operator import add
reduce(add, map(Counter, map(dict, res)))

Upvotes: 1

Ma0
Ma0

Reputation: 15204

You can flatten your original list with itertools.chain and then use tallying from collections.Counter

from itertools import chain
from collections import Counter


res = [[('CARDINAL', 1)], [('CARDINAL', 4)], [('CARDINAL', 1), ('ORG', 1)],
       [('CARDINAL', 1)], [('ORG', 1)], [('OTHER', 1)], [('CARDINAL', 1)]]

out = Counter()
for k, v in chain.from_iterable(res):
    out[k] += v
print(out)  # Counter({'CARDINAL': 8, 'ORG': 2, 'OTHER': 1})

That being said, I have the impression that the solution to your problem might be better placed before you get to this nested list you have (res).

Upvotes: 1

Related Questions