Charles Noon
Charles Noon

Reputation: 601

python .count for multidimensional arrays (list of lists)

How would I count the number of occurrences of some value in a multidimensional array made with nested lists? as in, when looking for 'foobar' in the following list:

list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]

it should return 2.

(yes I am aware that I could write a loop that just searches through all of it, but I dislike that solution as it is rather time-consuming, (to write and during runtime))

.count maybe?

Upvotes: 14

Views: 40304

Answers (3)

mfjones
mfjones

Reputation: 739

First join the lists together using itertools, then just count each occurrence using the Collections module:

import itertools
from collections import Counter

some_list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
totals = Counter(i for i in list(itertools.chain.from_iterable(some_list)))
print(totals["foobar"])

Upvotes: 7

Henrik Andersson
Henrik Andersson

Reputation: 47202

>> from collections import Counter
>> counted = Counter([item for sublist in my_list for item in sublist])
>> counted.get('foobar', 'not found!')
>> 2
#or if not found in your counter
>> 'not found!'

This uses flattening of sublists and then using the collections module and Counter to produce the counts of words.

Upvotes: 4

falsetru
falsetru

Reputation: 369274

>>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
>>> sum(x.count('foobar') for x in list)
2

Upvotes: 23

Related Questions