Filtering a list based on a list of booleans

后端 未结 6 1237
清歌不尽
清歌不尽 2020-11-27 10:14

I have a list of values which I need to filter given the values in a list of booleans:

list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
6条回答
  •  孤独总比滥情好
    2020-11-27 11:05

    With numpy:

    In [128]: list_a = np.array([1, 2, 4, 6])
    In [129]: filter = np.array([True, False, True, False])
    In [130]: list_a[filter]
    
    Out[130]: array([1, 4])
    

    or see Alex Szatmary's answer if list_a can be a numpy array but not filter

    Numpy usually gives you a big speed boost as well

    In [133]: list_a = [1, 2, 4, 6]*10000
    In [134]: fil = [True, False, True, False]*10000
    In [135]: list_a_np = np.array(list_a)
    In [136]: fil_np = np.array(fil)
    
    In [139]: %timeit list(itertools.compress(list_a, fil))
    1000 loops, best of 3: 625 us per loop
    
    In [140]: %timeit list_a_np[fil_np]
    10000 loops, best of 3: 173 us per loop
    

提交回复
热议问题