Marko
Marko

Reputation: 13

Counting number of occurrences in a row

If a have a list of n booleans, what would be the best way to find how many times true appears in a list once in a row, two times in a row and so on?

For an example: list1 = [True,False,True, True, False, False, False, True,True]

true appears once in row once, and two times in a row twice.

Upvotes: 0

Views: 61

Answers (1)

yatu
yatu

Reputation: 88236

You can use itertools.groupby to find consecutive occurrences of Trues and collections.Counter.

Lets try with the following list:

from itertools import groupby
from collections import Counter

l = [True, False, True, True, True, True, False, True]
Counter(sum(v) for k,v in groupby(l) if k)
# Counter({1: 2, 4: 1})

Upvotes: 3

Related Questions