英文:
Removing elements from sublists within a list in Python
问题
我有一个包含许多子列表的列表 A
。我想要从每个子列表中删除特定元素。例如,从 A[0]
中删除元素 0
,从 A[1]
中删除元素 1
,依此类推。但我遇到了一个错误。我展示期望的输出。
A=[[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
for i in range(0, len(A)):
A[i].remove(A[i] == i)
print(A)
错误是
in <module>
A[i].remove(A[i] == i)
ValueError: list.remove(x): x not in list
期望的输出是
[[2, 3, 5], [3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
英文:
I have a list A
containing many sublists. I want to remove specific element from each sublist. For example, remove element 0
from A[0]
, remove element 1
from A[1]
and so on. But I am getting an error. I present the expected output.
A=[[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
for i in range(0,len(A)):
A[i].remove(A[i]==i)
print(A)
The error is
in <module>
A[i].remove(A[i]==i)
ValueError: list.remove(x): x not in list
The expected output is
[[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]
答案1
得分: 2
你需要移除一个元素 `i`,但不移除条件 `A[i]==i`:
for i in range(len(A)):
A[i].remove(i)
英文:
You need to remove an item i
but not the condition A[i]==i
:
for i in range(len(A)):
A[i].remove(i)
答案2
得分: 1
更好的方法是枚举你的列表。还要确保你要删除的值实际上存在。使用try/except来处理这种情况
A = [[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
for i, e in enumerate(A):
try:
e.remove(i)
except ValueError:
pass
print(A)
输出:
[[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]
英文:
Probably better to enumerate your list. Also make sure that the value you're trying to remove actually exists. Use try/except to handle that scenario
A = [[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
for i, e in enumerate(A):
try:
e.remove(i)
except ValueError:
pass
print(A)
Output:
[[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论