I have a following list:
JavaScript
x
2
1
a = [[0, 1, 0, 1, 1, 1], [23,22, 12, 45, 32, 33],[232, 332, 222, 342, 321, 232]]
2
I want to remove 0
in a[0]
and corresponding values of a[1]
and [2]
, so the result list should be as follows:
JavaScript
1
2
1
d = [[1, 1, 1, 1], [22, 45, 32, 33], [332, 342, 321, 232]]
2
Advertisement
Answer
itertools.compress
is built for this task. Pair it with a listcomp to operate on each sublist, and force it to eagerly produce each new sublist, and you get what you want with fairly simple code:
JavaScript
1
8
1
from itertools import compress
2
3
a = [[0, 1, 0, 1, 1, 1], [23,22, 12, 45, 32, 33],[232, 332, 222, 342, 321, 232]]
4
5
new_a = [list(compress(sublst, a[0])) for sublst in a]
6
7
print(new_a)
8
Which outputs:
JavaScript
1
2
1
[[1, 1, 1, 1], [22, 45, 32, 33], [332, 342, 321, 232]]
2
Each call uses a[0]
as the selectors to determine which elements to keep from the data (each new sub-list
); when the selector value from a[0]
is falsy (0
here), the corresponding element is dropped, when it’s truthy (1
here) it’s retained.