In Python, how to efficiently extract sublist from a list based on a list of 0/1, where locations with 1 is selected?

Question:

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!

Asked By: ExcitedSnail

||

Answers:

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).

Answered By: John Coleman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.