Skip to content Skip to sidebar Skip to footer

Match Character From String With Binary List

With string abcdefg and list [1, 1, 0, 0, 1, 1, 0], what is a Pythonic way to return all characters in the string that match 1 (on) in the list? The desired output will be: ['a',

Solution 1:

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 latest 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']

Solution 2:

[x[0] for x in zip("abcdefg", [1, 1, 0, 0, 1, 1, 0]) if x[1]]

Solution 3:

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 prefered one is the one with iter() : no zip, no enumerate, no itertool


Solution 4:

Regarding your update - you an use itertools.groupby to identify runs of consecutive values, and build a list from that - eg:

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

Post a Comment for "Match Character From String With Binary List"