zdm
zdm

Reputation: 531

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

Upvotes: 4

Views: 378

Answers (2)

jpp
jpp

Reputation: 164693

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)]

Upvotes: 5

Mr. T
Mr. T

Reputation: 12410

One easy way is to use two nested loops. As you have probably noticed by now, you need two index numbers - one for the list in A and another for the element number of this list. Here is one way to tackle the problem:

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]]

#cycle through list A and keep track of the list number i
for i, a_list in enumerate(A):
    #retrieve index from each list in A, start with the highest index to avoid index problems
    for j in sorted(a_list, reverse = True):
        #delete the element j in list i of W
        del W[i][j]

print(W)
#output
#[[2], [3], [3], [4, 4], []]

Upvotes: 2

Related Questions