How to remove elements from multiple sublists according to another sublist in Python
Question:
I have a list J
and removing elements from J
according to index
. I am trying to remove elements of J[0]=[2, 6, 9, 10]
according to index[0]=[0,3]
. Now after removing, I have J=[6,9]
which should append to create [[2, 6, 9, 10], [6, 9]]
. Now it should take [6,9]
and remove element according to index[1]=[1]
. I present the current and expected outputs.
J=[[2, 6, 9, 10]]
index=[[0,3],[1]]
u=0
for v in range(0,len(index)):
new_J = [j for i, j in enumerate(J[u]) if i not in index[v]]
J.append(new_J)
print(J)
The current output is
[[2, 6, 9, 10], [6, 9], [2, 9, 10]]
The expected output is
[[2, 6, 9, 10], [6, 9], [6]]
Answers:
Just take your example, try this:
J=[[2, 6, 9, 10]]
index=[[0,3],[1]]
u=0
for v in range(0,len(index)):
new_J = [j for i, j in enumerate(J[-1]) if i not in index[v]]
J.append(new_J)
print(J)
You can apply itertools.accumulate
:
from itertools import accumulate
J = [[2, 6, 9, 10]]
idx = [[0,3], [1]]
J = list(accumulate(idx, lambda lst, idx: [v for i, v in enumerate(lst) if i not in idx],
initial=J[-1]))
[[2, 6, 9, 10], [6, 9], [6]]
I have a list J
and removing elements from J
according to index
. I am trying to remove elements of J[0]=[2, 6, 9, 10]
according to index[0]=[0,3]
. Now after removing, I have J=[6,9]
which should append to create [[2, 6, 9, 10], [6, 9]]
. Now it should take [6,9]
and remove element according to index[1]=[1]
. I present the current and expected outputs.
J=[[2, 6, 9, 10]]
index=[[0,3],[1]]
u=0
for v in range(0,len(index)):
new_J = [j for i, j in enumerate(J[u]) if i not in index[v]]
J.append(new_J)
print(J)
The current output is
[[2, 6, 9, 10], [6, 9], [2, 9, 10]]
The expected output is
[[2, 6, 9, 10], [6, 9], [6]]
Just take your example, try this:
J=[[2, 6, 9, 10]]
index=[[0,3],[1]]
u=0
for v in range(0,len(index)):
new_J = [j for i, j in enumerate(J[-1]) if i not in index[v]]
J.append(new_J)
print(J)
You can apply itertools.accumulate
:
from itertools import accumulate
J = [[2, 6, 9, 10]]
idx = [[0,3], [1]]
J = list(accumulate(idx, lambda lst, idx: [v for i, v in enumerate(lst) if i not in idx],
initial=J[-1]))
[[2, 6, 9, 10], [6, 9], [6]]