Meet the characters from a string with a binary list

With the string abcdefg and list [1, 1, 0, 0, 1, 1, 0] , what is the Pythonic way to return all the characters in a string that matches 1 (on) in the list?

The desired result will be:

 ['a', 'b', 'e', 'f'] 

Thanks!

Edit:

Another question: is it possible to group ab and ef so that the result looks something like this: ['ab', 'ef'] ? Basically, the idea is to group characters separated by 0 . If not 0 , then it will be ['abcdefg'] . Thanks!

+1
source share
4 answers

You can use itertools.compress for this purpose.

 >>> from itertools import compress >>> list(compress("abcdefg", [1, 1, 0, 0, 1, 1, 0])) ['a', 'b', 'e', 'f'] 

If you do not want to import any modules, you can also use

 >>> [e for e, i in zip("abcdefg", [1, 1, 0, 0, 1, 1, 0]) if i] ['a', 'b', 'e', 'f'] 

Based on your last requirement

 >>> from itertools import groupby >>> st = "abcdefghijklm" >>> some_list = [1,1,0,0,0,1,1,1,0,0,0,1,0] >>> it_l = iter(some_list) >>> [''.join(v) for k, v in groupby(st, key = lambda e:next(it_l)) if k] ['ab', 'fgh', 'l'] 

or better

 >>> [''.join(zip(*v)[-1]) for k, v in groupby(zip(some_list, st), key = itemgetter(0)) if k] ['ab', 'fgh', 'l'] 
+4
source
 [x[0] for x in zip("abcdefg", [1, 1, 0, 0, 1, 1, 0]) if x[1]] 
+2
source

Three solutions:

 s = 'abcdefg' li = [1, 1, 0, 0, 1, 1, 0] print [c for i,c in enumerate(s) if li[i]] print [s[i] for i,b in enumerate(li) if b] it = iter(li) print [c for c in s if it.next()] 

My preferred one is with iter (): no zip, no enumerate, no itertool

+1
source

As for your update, you can use itertools.groupby to determine runs of sequential values ​​and build a list from it - for example:

 text = 'abcdefg' bits = [1, 1, 0, 0, 1, 1, 0] from itertools import groupby print [''.join(el[0] for el in g) for k, g in groupby(zip(text, bits), lambda L: L[1]) if k] # ['ab', 'ef'] 
+1
source

All Articles