First, you need to define your filter structure, to define which positions will remain in the list and which will be removed. To do this, simply create a list that has True
at positions where the value in lista1
is positive and False
otherwise.
filtro = [valor1 > 0 for valor1 in lista1]
This will generate the list [True, False, True, False]
indicating what remains and what will come out.
Note: here it is important that filtro
be a list (and not a generator), as below it will be consumed more than once (generator will not allow this).
From there just use the function itertools.compress
:
from itertools import compress
nova_lista1 = list(compress(lista1, filtro))
nova_lista2 = list(compress(lista2, filtro))
Thus, nova_lista1
will be [2, 4]
and nova_lista2
will be [1, 4]
.
The very function compress
returns an eternal object, so if you don’t need all the values in memory you can use the return itself instead of generating a new list (proper).
In a much more iterative way, you could scroll through the two lists generating the new ones when the condition is satisfied:
lista1 = [2, -1 , 4, -5]
lista2 = [1, 2, 4, 9]
nova_lista1 = []
nova_lista2 = []
for valor1, valor2 in zip(lista1, lista2):
if valor1 > 0:
nova_lista1.append(valor1)
nova_lista2.append(valor2)
What would generate the same result.
What would be the expected result for this example?
– Woss
novaLista1 = [2, 4] and novaLista2 = [1, 4] As the element of the list1 is positive, I take the element of list1 and Lista2 at the same position and add it in different lists
– Paulo