Python: Elegant and efficient ways to mask a list

后端 未结 5 1358
情深已故
情深已故 2020-12-05 14:26

Example:

from __future__ import division
import numpy as np

n = 8
\"\"\"masking lists\"\"\"
lst = range(n)
print lst

# the mask (filter)         


        
5条回答
  •  我在风中等你
    2020-12-05 14:46

    If you are using Numpy, you can do it easily using Numpy array without installing any other library:

    >> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >> msk = [ True, False, False,  True,  True,  True,  True, False, False, False]
    >> a = np.array(a) # convert list to numpy array
    >> result = a[msk] # mask a
    >> result.tolist()
    [0, 3, 4, 5, 6]
    

提交回复
热议问题