pythonlistnumpy

Changing objects in a Python list according to boolean/binary vector


Let

L=[-1, 3, 4, -2, 6]

be a list and

indices=np.array([1, 0, 0, 1,1], dtype=bool)

a boolean vector. I would like to set the entries of L according to indices, e.g. L[indices]= an object OBJ, so that the outcome is [OBJ, 3, 4, OBJ, OBJ].

If possible, OBJ should be something such that, when performing its dot product with any sparse vector, the result is again OBJ in a very efficient way. Something like OBJ=[], or None makes any sense?

Thanks a lot for your help!

I tried L[indices]=OBJ as if L were an array, but i get an error.


Solution

  • import numpy as np
    L=[-1, 3, 4, -2, 6] 
    indices=np.array([1, 0, 0, 1,1], dtype=bool)
    
    [None if b else e for e,b in zip(L, indices)]
    

    results in [None, 3, 4, None, None]

    is that what you mean?