Filtering two lists at the same time

I have three lists:

del_ids = [2, 4] ids = [3, 2, 4, 1] other = ['a', 'b', 'c', 'd'] 

and my goal is to remove del_ids with the result

 ids = [3, 1] other = ['a', 'd'] 

I tried to make a mask for the elements to be saved ( mask = [id not in del_ids for id in ids] ), and I plan to apply this mask in both lists.

But I feel that this is not a Python solution. Could you tell me how I can do this better?

+4
source share
2 answers

close, filter and unzip again:

 ids, other = zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids)) 

The zip() parameter calls each id with the corresponding other element, the generator expression filters any pair where id is specified in del_ids , and zip(*..) then teases the remaining ones again, add the pairs to separate lists.

Demo:

 >>> del_ids = [2, 4] >>> ids = [3, 2, 4, 1] >>> other = ['a', 'b', 'c', 'd'] >>> zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids)) [(3, 1), ('a', 'd')] 
+8
source

zip, filter, unzip:

 ids, other = zip(*filter(lambda (id,_): not id in del_ids, zip(ids, other))) 
+1
source

Source: https://habr.com/ru/post/1494742/


All Articles