Reputation: 13
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
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