Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a list of indices from list

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

like image 981
zdm Avatar asked Mar 06 '23 03:03

zdm


1 Answers

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)]
like image 108
jpp Avatar answered Mar 16 '23 11:03

jpp