I have two lists of lists of the same length in Python 3 as follows:
A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]]
W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]]
Elements of A
are indices of elements of W
. I would like to remove the elements of W
given A
. So, in the example, I would like to remove W[0][0]
, W[1][0]
, W[1][1]
, W[2][0]
, W[2][1]
, W[2][2]
, etc.
What I did is this:
for t in range(len(A)):
del W[t][A[t]]
But this gives the following error: TypeError: list indices must be integers or slices, not list
Unlike numpy
arrays, you cannot index a list with a list. But you can use a list comprehension for this task:
A = [[0], [0, 1], [0, 1, 2], [0, 1], [0, 1, 2, 3]]
W = [[2, 2], [1, 2, 3], [2, 2, 2, 3], [1, 3, 4, 4], [1, 1, 3, 4]]
res = [[j for i, j in enumerate(w) if i not in a] for a, w in zip(A, W)]
print(res)
[[2], [3], [3], [4, 4], []]
Or, if you are happy using a 3rd party library, numpy
syntax is simpler:
import numpy as np
res = [np.delete(i, j).tolist() for i, j in zip(W, A)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With