1

I need to create a function or equation that will turn this input...

a = [True, False, True]
b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

into this output...

c = [[1, 3], [4, 6], [7, 9]]

Note: the above arrays are all numpy arrays. Thanks!

2
  • then add numpy tag Commented Oct 2, 2017 at 18:22
  • Something like [[e for x, e in zip(a, sublist) if x] for sublist in b] will work but I suspect there's a more efficent numpy solution Commented Oct 2, 2017 at 18:25

2 Answers 2

7

numpy solution

import numpy as np 
a = np.array([True, False, True])
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b[:,a]

array([[1, 3],
       [4, 6],
       [7, 9]])
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, makes much more sense +1
2

You can use itertools compress

from itertools import compress
c = [list(compress(i, a)) for i in b]

[[1, 3], [4, 6], [7, 9]]

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.