Reputation: 97
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?
Upvotes: 4
Views: 365
Reputation: 11696
No regex needed, just str.split
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]
Upvotes: 1
Reputation: 114025
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in re.split("0+", mystr) if s]
[4, 3, 1, 2, 4]
Upvotes: 1
Reputation: 21914
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))
Upvotes: 2
Reputation: 142206
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]
Upvotes: 15
Reputation: 437
>>> s = "000000111100011100001011000000001111"
>>> items = set(s)
>>> counts = [s.count(x) for x in items]
>>> counts
[1, 1]
>>>
Upvotes: -6