2

I have a 2 lists as detailed below:

a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
remove_a_index = [[0], [0, 2, 3], [1]]

What is the best solution to remove list index of a base on the number from remove_a_index for e.g. for a[0] I need to remove number 0

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Ronalkiha
  • 129
  • 3
  • 12

5 Answers5

2

You may use a nested list comprehension expression using zip() and enumerate() to filter the content as:

>>> a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
>>> remove_a_index = [[0], [0, 2, 3], [1]]

>>> a = [[j for i, j  in enumerate(x) if i not in y] for x, y in zip(a, remove_a_index)]
# where new value of `a` will be:
# [[1, 1, 2], [5], [2, 3, 3]]

Based on your desired result, in case if you just want to remove zeroes from the a list then you don't need the intermediate remove_a_index list. You may use a list comprehension expression to skip the zeroes from the new list as:

>>> a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]

>>> [[j for j in i if j!=0] for i in a]
[[1, 1, 2], [5], [2, 3, 3]]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

If I understood correctly the question, this should work:

for i, to_remove in enumerate(remove_a_index):
    for j in reversed(to_remove):
        del a[i][j]
user1620443
  • 784
  • 3
  • 14
1

Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3:

As an example, if I have l1 = [1,2,6,8] and l2 = [2,3,5,8], l1 - l2 should return [1,6]:

l3 = [x for x in l1 if x not in l2]
l3 will contain [1, 6].
halfer
  • 19,824
  • 17
  • 99
  • 186
Aditya
  • 2,380
  • 2
  • 14
  • 39
0

You can do the following:

  1. Create a new list.
  2. Modify the all the items that you wish to remove to 'remove' on the original list.
  3. Populate the new list with all the items that are not 'remove'.

The code:

a_new=[]
for i, item in enumerate(a):
    for element_to_remove in remove_a_index[i]:
        item[element_to_remove]='remove'

    new_item = [element  for element in item if element!='remove']
    a_new.append(new_item)
a=a_new
Amit Wolfenfeld
  • 603
  • 7
  • 9
0

The shortest one-liner is below:

a = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
remove_a_index = [[0], [0, 2, 3], [1]]

b = [[y for y in original_tuple if y not in remove_a_index[index]] for index, original_tuple in enumerate(a)]
print b

To explain, it's using list comprehension to loop through a and use the index:

[? for index, original_tuple in enumerate(a)]

At this point the index is (0, 1, 2...) and original_tuple is each tuple.

Then for each tuple, you can access the subtracting tuple (remove_a_index[x]) by checking if it's in it or not.

[y for y in original_tuple if y not in remove_a_index[index]] ...
ergonaut
  • 6,929
  • 1
  • 17
  • 47