Search code examples
pythonlistnumpylogical-operatorsmasking

bitwise OR reduction of python lists


I have two lists of zeros and ones. Both lists are of same length. The following is just an example, i am looking for a generic solution for lists of any sizes and with zeros and ones at any index.

l1 = [1,1,0,1,1,1,1]
l2 = [0,0,0,1,0,0,0]

The goal is to use the first list l1 as mask to create a new list l2_new from l2 that logicaly OR merges all elements of indizes where l1 is 1 and adopts elements unchanged where l1 is 0.

Which would result to:

l2_new = [0,0,1]

Graphical explanation:

enter image description here


Solution

  • That's a perfect setup for np.bitwise_or.reduceat that does slice-based OR-ing -

    # Based on https://stackoverflow.com/a/62430810/ @Divakar
    def squash1s_mask(a):
        a = np.asarray(a)
        m = a==1
        return np.r_[True,m[:-1]!=m[1:]] | (a==0)
    
    out = np.bitwise_or.reduceat(l2, np.flatnonzero(squash1s_mask(l1)))