如何根据另一个子列表从多个子列表中移除元素在Python中

huangapple go评论97阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月1日 15:20:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定