Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find if element appears n times in a row in python list

Tags:

python

list

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?

like image 412
user2333196 Avatar asked Dec 20 '22 10:12

user2333196


1 Answers

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.

like image 152
Martijn Pieters Avatar answered Jan 21 '23 23:01

Martijn Pieters