英文:
How to remove elements from multiple sublists according to another sublist in Python
问题
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]]
英文:
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]]
答案1
得分: 1
只需使用您的示例,尝试这样做:
```python
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)
<details>
<summary>英文:</summary>
Just take your example, try this:
```python
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)
答案2
得分: 1
你可以使用 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]]
英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论