I am new to Python, and now I am encountered with this question to count occurrences of consecutive True values in nested list or two dimensional numpy array filled with Booleans. Say I have a nested list like listX = [[True, False, True, True, True], [False, True, True, False, True], [False, True, False, False, False], [True, True, False, False, True]]
. I want to count the occurrences of consecutive True values in each list, i.e. for listX[0], I would want the answer to be [1,3]
. (In reality, I can have 10-25 flexible number of lists inside the nested list and each list contains 100 Boolean values.)
Based on the itertools
mentioned in the answer for a previous question with one dimensional array
Count consecutive occurences of values varying in length in a numpy array, I can answer my simple example like this:
listX = [[True, False, True, True, True], [False, True, True, False, True], [False, True, False, False, False], [True, True, False, False, True]]
import numpy as np
arr = np.array(listX)
arr
>>> array([[ True, False, True, True, True],
[False, True, True, False, True],
[False, True, False, False, False],
[ True, True, False, False, True]])
import itertools
c1 = [sum(1 for _ in group) for key, group in itertools.groupby(arr[0]) if key]
c2 = [sum(1 for _ in group) for key, group in itertools.groupby(arr[1]) if key]
c3 = [sum(1 for _ in group) for key, group in itertools.groupby(arr[2]) if key]
c4 = [sum(1 for _ in group) for key, group in itertools.groupby(arr[3]) if key]
c1, c2, c3, c4
>>> ([1, 3], [2, 1], [1], [2, 1])
Since the example here just have 4 rows, I can code this way with indexing each row for 2D array, but in reality, I can have 10-25 flexible number of rows and each row contains 100 Boolean values. Is there any simpler way than this?