Home > Software design >  Binary String to List Python
Binary String to List Python

Time:10-10

I've got a binary string like '1100011101'. I would like to parse it into a list where each chunk of 1's or 0's is a separate value in the list.

Such as: '1100011101' becomes ['11', '000', '111', '0', '1']

CodePudding user response:

Use itertools.groupby:

from itertools import groupby

binary = "1100011101"

result = ["".join(repeat) for _, repeat in groupby(binary)]
print(result)

Output

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

CodePudding user response:

You can scrape a (minor) bit of performance out of this by using a regex instead of groupby() join(). This just finds groups of 1 or 0:

import re

s = '1100011101'
l = re.findall(r"0 |1 ", s)
# ['11', '000', '111', '0', '1']

Timings:

s = '1100011101' * 1000

%timeit l = [''.join(g) for _, g in groupby(s)]
# 1.16 ms ± 9.79 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit re.findall(r"0 |1 ", s)
# 723 µs ± 5.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

CodePudding user response:

with groupby

>>> from itertools import groupby as f
>>> x = str(1100011101)
>>> sol = [''.join(v) for k, v in f(x)]
>>> print(sol)
['11', '000', '111', '0', '1']

without using groupby

def func(binary: str):
    tmp = []
    for i in binary:
        if tmp and  tmp[-1]!=i:
            tmp.append(' ')
        tmp.append(i)
    return ''.join(tmp).split(' ')
        
    x = '1100011101'
    sol =func(x)
    print(sol)

output

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

CodePudding user response:

Insert a space between the 01 and 10 transitions using .replace() and then split the resulting string:

'1100011101'.replace("01","0 1").replace("10","1 0").split()

['11', '000', '111', '0', '1']
  • Related