Let's say I have a string of the following form:
"000000111100011100001011000000001111"
and I want to create a list containing the lengths of the 1-streaks:
[4, 3, 1, 2, 4]
Is there a nice one-liner for this?
If you don't mind the from itertools import groupby
...
>>> from itertools import groupby
>>> [len(list(g)) for k, g in groupby(s) if k == '1']
[4, 3, 1, 2, 4]
Can be done with regex, though not quite as elegant as the itertools solutions
answer = [len(item) for item in filter(None, re.split(r"[^1]+", test_string))]
Or, more elegant:
answer = [len(item) for item in re.findall(r"1+", test_string)]
and more elegant still (credits to Jon):
answer = map(len, re.findall("1+", test_string))
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