Replacing a string by the number of stripes

Let's say I have a line like this:

"000000111100011100001011000000001111" 

and I want to create a list containing 1-strip lengths:

 [4, 3, 1, 2, 4] 

Is there a nice one-line font for this?

+4
source share
5 answers

If you do not mind 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] 
+15
source

Can be done with regex, although not as elegant as itertools solutions

 answer = [len(item) for item in filter(None, re.split(r"[^1]+", test_string))] 

Or, more elegantly:

 answer = [len(item) for item in re.findall(r"1+", test_string)] 

and even more elegant (Jon loans):

 answer = map(len, re.findall("1+", test_string)) 
+2
source
 >>> mystr = "000000111100011100001011000000001111" >>> [len(s) for s in re.split("0+", mystr) if s] [4, 3, 1, 2, 4] 
+1
source

No regex needed, just str.split

 >>> mystr = "000000111100011100001011000000001111" >>> [len(s) for s in mystr.split('0') if s] [4, 3, 1, 2, 4] 
+1
source
 >>> s = "000000111100011100001011000000001111" >>> items = set(s) >>> counts = [s.count(x) for x in items] >>> counts [1, 1] >>> 
-6
source

Source: https://habr.com/ru/post/1492616/


All Articles