英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论