从Python中的列表中删除子列表中的元素

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

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

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

发表评论

匿名网友

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

确定