Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python .count for multidimensional arrays (list of lists)

Tags:

python

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?

like image 278
Charles Noon Avatar asked Jul 18 '13 08:07

Charles Noon


People also ask

How do you compare two multidimensional lists in Python?

The set() function and == operator Python set() function manipulate the list into the set without taking care of the order of elements. Besides, we use the equal to operator (==) to compare the data items of the list.

How do I count a list inside a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

Can a list be 2 dimensional Python?

Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.


2 Answers

>>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
>>> sum(x.count('foobar') for x in list)
2
like image 101
falsetru Avatar answered Oct 22 '22 03:10

falsetru


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"])
like image 41
mfjones Avatar answered Oct 22 '22 04:10

mfjones