0

I have two lists:

A: [ True  True  True False  True False  True ]
B: ['A', 'B', 'C', 'D', 'E', 'F', 'G']

I want to get only those values from list B where list A is True.

Desired output:

['A', 'B', 'C', 'E', 'G']

4 Answers 4

2

You can use itertools.compress(...):

import itertools
a = [ True, True, True, False, True, False, True ]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

ab = itertools.compress(b, a)
print(list(ba))
Sign up to request clarification or add additional context in comments.

Comments

1

If you do not want to import itertools, simple list comprehension with zip built-in function would be enough.

conditions =  [True, True, True, False, True, False, True]
objects = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
result = [o for o, c in zip(objects, conditions) if c]
assert result == ['A', 'B', 'C', 'E', 'G']

Comments

0

Fairly simple problem to be posted as a question; here is the solution. Would appreciate if you could try it before asking here.

Code:

a = [True, True, True, False, True, False, True]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
res = []
for x in range(len(a)):
    if a[x]==True:
        res.append(b[x])
print res

Output:

['A', 'B', 'C', 'E', 'G']

Comments

0

I hope this works for python 2 as well; I have only 3 on this PC, but still:

a = [ True, True, True, False, True, False, True ]
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
ab = []

for i, j in enumerate(a):
    if j == True:
        ab.append(b[i])
# in python 3 this was print(ab) :) I ported :)
print ab

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.