Removing elements of one list with respect to another list in Python


I have two lists A and B. I am removing element from A which is less than tol. But I also want to remove element from B corresponding to the removed element from A. For example, [[2.22105075e-18]] was removed from A. Corresponding to this, [[4,13]] should be removed from B. I present the current and expected output.

import numpy as np
A= [[9.16435586e-05], [0.000184193464], [9.28353239e-05], [2.22105075e-18]]
B= [[13, 14], [4, 5], [5, 14], [4, 13]]

CA=[[x[0]] for x in A if x[0]>tol]
CB=[x for x,y in enumerate(CA) if list(y) in B]

The current output is


The expected output is

[[13, 14], [4, 5], [5, 14]]

>Solution :

You could process the two in parallel with zip:

CA, CB = map(list, zip(*((a, b) for a, b in zip(A, B) if a[0]>tol)))

# or
# CA, CB = map(list, zip(*(x for x in zip(A, B) if x[0][0]>tol)))


# CA
[[9.16435586e-05], [0.000184193464], [9.28353239e-05]]

# CB
[[13, 14], [4, 5], [5, 14]]

Leave a Reply Cancel reply