从另一个列表中的索引中移除列表中的元素在Python中。

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

Removing elements from a list based on indices in another list in Python

问题

我有一个列表```J```。我想根据```index``````J[0]```中删除特定元素例如我想基于```index```中的元素删除```J[0],J[3]```。但是我遇到了一个错误我展示了期望的输出

```python
J=[[2, 6, 9, 10]]

index=[[0,3]]

for i in range(0,len(J)):
    for k in range(0,len(index)): 
        J[i].remove(index[k][0])
print(J)

错误是

 in <module>
    J[i].remove(index[k][0])

ValueError: list.remove(x): x not in list

期望的输出是

[6,9]

<details>
<summary>英文:</summary>

I have a list ```J```. I want to remove specific elements from ```J[0]``` based on ```index```. For example, I want to remove ```J[0],J[3]``` based on elements in ```index```. But I am getting an error. I present the expected output.

J=[[2, 6, 9, 10]]

index=[[0,3]]

for i in range(0,len(J)):
for k in range(0,len(index)):
J[i].remove(index[k][0])
print(J)


The error is

in <module>
J[i].remove(index[k][0])

ValueError: list.remove(x): x not in list


The expected output is

[6,9]



</details>


# 答案1
**得分**: 1

尝试使用列表推导/过滤(并根据需要修复`[0]`):

```python
new_J = [j for i, j in enumerate(J[0]) if i not in index[0]]
英文:

Try list comprehension / filtering (and fix the [0] as required):

new_J = [j for i,j in enumerate(J[0]) if i not in index[0]]

答案2

得分: 1

在这段代码中,您的代码循环仅一次用于j和index,因为len(j)和len(index)都为1。

尝试这样做:

J=[2, 6, 9, 10]

index=[0,3]

for i in range(len(index)):
    J.pop(index[i] - i)

print(J)
英文:

Well in this code you loop your code only 1 time for j and index because both len(j) and len(index) is 1.

Try this:

J=[2, 6, 9, 10]

index=[0,3]

for i in range(len(index)):
    J.pop(index[i] - i)

print(J)

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

发表评论

匿名网友

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

确定