Format string by binary list

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

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0] stackoverflow 

Is it possible to get a new line like -tc-over---- which follows:

 [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0] - t - c - over - - - - 

That is, each character corresponding to 0 will be replaced as - . The desired result would be a list, as shown below, with letters matching 1 , and matching hyphen 0s are grouped separately:

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

Thanks!

+4
source share
4 answers

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

 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))] 

Thus, the output will be:

 ['-', 't', '-', 'c', '-', 'over', '----'] 
+3
source

How about something like that? Replace the two lists and iterate and build the output. Store the last binary value to determine whether to add 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('(-+|[az]+)', x) print(output) 
+4
source

the answer to your last question could be slightly modified to get the desired result

First answer:

Considering

 [''.join(v) for k, v in groupby(st, key = lambda e:next(it_lst))] 

Modified

 [''.join(v if k else ('-' for _ in v)) for k, v in groupby(st, key = lambda e:next(it_lst))] 

Second answer

Considering

 [''.join(zip(*v)[-1]) for k, v in groupby(zip(lst, st), key = itemgetter(0)) if k] 

Modified

 [''.join(zip(*v)[-1] if k else ('-' for _ in v)) for k, v in groupby(zip(lst, st), key = itemgetter(0))] 

Note All you have to do is

  • Stop ignoring records 0
  • For each element 0 create a string of length equal to the grouped string of 0
+1
source

You can do it:

 string = "stackoverflow" arr = [0,1,1,0,1,0,1,0,1,0,0,1,0] new = "" for i in range(len(arr)): new += string[i]*arr[i] +"-"*(abs(arr[i]-1)) 

this means that the string times 0 is an empty string.

You can then split it into a list of strings using regex

 import re list = re.findall("-+|[Az]+", new) 

"-+|[Az]+" matches patterns that are either a hyphen string longer than 1 or a string of letters longer than 1.

+1
source

All Articles