laszlopanaflex
laszlopanaflex

Reputation: 1916

filter a list based on values in another list

list1 = ['a','b','c','d']
list2 = [1,0,1,0]

Given two lists like the above, I would like to obtain a third list whose values are ['a','c']

In other words, I'd like the target list to be the values from list1 where the corresponding element in list2 is 1.

Upvotes: 0

Views: 2087

Answers (3)

pygeek
pygeek

Reputation: 7404

Use enumerate function on second list to include index, which can be used for the first list.

[list1[i] for i, item in enumerate(list2) if item]

Upvotes: 1

neutrino_logic
neutrino_logic

Reputation: 1299

Generators can be nice if you have very long lists:

def filterfunc(a, b, keyvalue=1):
    return (x for i, x in enumerate(a) if b[i] == keyvalue)

To get the whole sequence:

list(filterfunc(a, b))

Upvotes: 0

HHC
HHC

Reputation: 79

As noted in the comments:

[i for i, j in zip(list1, list2) if j] would work.

Alternatively, if you were looking for something not so advanced:

list3 = []

for i in range(len(list1)):
    if list2[i] == 1:
        list3.append(list1[i])

Upvotes: 1

Related Questions