Home > OS >  In Python, how to efficiently extract sublist from a list based on a list of 0/1, where locations wi
In Python, how to efficiently extract sublist from a list based on a list of 0/1, where locations wi

Time:10-25

I have a list called all=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and another list called sub=[1, 0, 1, 0, 1, 1, 0, 0, 0, 0], I want to create a new list based on all by extracting only elements whose corresponding value in the list named sub is 1, i.e., I want to generate aa=[0,2,4,5]. It would be great if this could be done as fast as possible as I need to repeat this more than 10 millions of times.

I've tried the following two ways:

(1).

aa=all[sub]

But I got the message "TypeError: list indices must be integers or slices, not list"

(2).

bv=list(map(bool,sub))
aa=all[bv]

But I got the same error message.

How to solve this problem? Thanks!

CodePudding user response:

You could do it with a simple list comprehension:

aa = [x for x,s in zip(lst,sub) if s == 1]

You would need to time it to see if it is fast enough for your needs.

(As an aside using all as the list name overwrites the built-in function with the same name).

  • Related