myList = [True, True, False, False, True, False, True, False, False]
I want to find if True appears 3 times in a row.
I can find it by doing:
for x0, x1, x2 in zip(myList, myList[1:], myList[2:]):
if x0 == True and x1 == True and x2 == True:
print True
Is there a better way?
Use itertools.groupby()
to group elements, then count each group. Using the any()
function lets you exit the loop early if a match was found:
from itertools import groupby, islice
print any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
The if k
filters the groups to only count the groups of True
values.
The itertools.islice()
function ensures we only look at the first 3 elements of a group, and ignore the rest of that group. This way you avoid having to count the next however many True
values just to determine that you found at least 3.
Demo:
>>> from itertools import groupby, islice
>>> myList = [True, True, False, False, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 1, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
False
>>> myList = [True, True, False, False, True, True, True, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 3, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
True
I used a list comprehension to show the group sizes (counting only True
groups) to show why the any()
call returns False
first, then True
; the second example has a group of 4 consecutive True
values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With