user3530769 user3530769 -4 years ago 98
Python Question

python remove list index base on another lists

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

Answer Source

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]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download