Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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!
numpy
[[e for x, e in zip(a, sublist) if x] for sublist in b]
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]])
Add a comment
You can use itertools compress
from itertools import compress c = [list(compress(i, a)) for i in b] [[1, 3], [4, 6], [7, 9]]
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
numpytag[[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