What I am trying to do is to find out how many sequences of '1' are in a list read from the user input. For example, if my list looks like:
mylist = [0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1]
, then I want to print '3', because I have 3 sequences of 1.
So far I have tried to find the indexes of '0' and see if those indexes are consecutive(which means is a sequence of 1 between my 2 zero's, but with no success.
You can use itertools.groupby
in a generator expression for sum
:
from itertools import groupby
sum(1 for k, _ in groupby(mylist) if k)
This returns: 3
If you know your list is just going to be made up of ones and zeroes, then you can join everything together as a string, split the string on every occurrence of '0', and then count up all of the strings of 1s (which will be any part that's not empty).
>>> mylist = [0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1]
>>> chunks_o_ones = [i for i in ''.join([str(i) for i in mylist]).split('0') if len(i) > 0]
>>> print(len(chunks_o_ones))
3
You could alternatively take the string and use a regular expression to find the '1' blocks:
>>> import re
>>> p = re.compile('1+')
>>> print(len(p.findall(''.join([str(i) for i in mylist]))))
3
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