Skip to content
Advertisement

Remove all elements in each list of a nested list, based on first nested list

I have a following list:

JavaScript

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

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

Which outputs:

JavaScript

Try it online!

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement