Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string by binary list

Tags:

python

With a string and a binary list of the same length, for example:

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
 s  t  a  c  k  o  v  e  r  f  l  o  w

Is it possible to obtain a new string as -t-c-over---- that follows:

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
 -  t  -  c  -  o  v  e  r  -  -  -  -

That is, each character matching with 0 will be replaced as -. The desired output would be a list as below with letters matching 1 and hyphens matching 0 are grouped separately:

['-', 't', '-', 'c', '-', 'over', '----']

Thanks!

like image 587
Rock Avatar asked Jan 15 '23 01:01

Rock


2 Answers

How about something like this? Zip the two lists and iterate and build the output. Keep the last binary value to determine whether you should append or concat.

blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'
output = []    
previous = not blist[0] # to cause the first char to be appended

for b,s in zip(blist, string):
    char = '-' if b == 0 else s

    if previous == b:
        output[-1] += char         
    else:
        output.append(char)

    previous = b

print(output)

Another option is regex:

import re

blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'

x = ''.join(['-' if b == 0 else s for b,s in zip(blist, string)])
output = re.findall('(-+|[a-z]+)', x)

print(output)
like image 161
jurgenreza Avatar answered Jan 19 '23 11:01

jurgenreza


You can have fun with iterators (no zip needed! :)

it = iter([0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0])
s = 'stackoverflow'

output = [''.join(('-' for i in b) if not a else b)
          for a,b in 
          itertools.groupby(s, key=lambda x: next(it))]

So output will be:

['-', 't', '-', 'c', '-', 'over', '----']
like image 43
JBernardo Avatar answered Jan 19 '23 12:01

JBernardo