Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split '000111010010111' into ['000','111','0',1','00','1','0','111'] [duplicate]

Tags:

python-3.x

Is there some concise way to split up a string of 0s and 1s into the homogeneous, contiguous segments of all 0s and all 1s? Example in the title.

I can of course do it with a nested loop, conditionals, and the .count() method, but this seems like something there'd be a library function for. I'm just not sure how to search for it if there is.

like image 713
Bobbie D Avatar asked Sep 19 '25 15:09

Bobbie D


1 Answers

Yes you can using itertools.groupby

from itertools import groupby
a = "000111010010111"
result = ["".join(list(group)) for key, group in groupby(a)]

What happened? We used itertools.groupby to group consecutive terms. A new group is created every time the key element changes (which is when a 0 turns into a 1 or a 1 turns into a 0 in your example). The inner lists are then joined to arrive at your desired output.

Output:

['000', '111', '0', '1', '00', '1', '0', '111']

This will work for any string (not just 1s and 0s) and will group items together based on their consecutive appearances.

like image 178
SyntaxVoid supports Monica Avatar answered Sep 21 '25 07:09

SyntaxVoid supports Monica