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

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

Removing elements from sublists within a list in Python

问题

我有一个包含许多子列表的列表 A。我想要从每个子列表中删除特定元素。例如,从 A[0] 中删除元素 0,从 A[1] 中删除元素 1,依此类推。但我遇到了一个错误。我展示期望的输出。

  1. A=[[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
  2. for i in range(0, len(A)):
  3. A[i].remove(A[i] == i)
  4. print(A)

错误是

  1. in <module>
  2. A[i].remove(A[i] == i)
  3. ValueError: list.remove(x): x not in list

期望的输出是

  1. [[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.

  1. A=[[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
  2. for i in range(0,len(A)):
  3. A[i].remove(A[i]==i)
  4. print(A)

The error is

  1. in <module>
  2. A[i].remove(A[i]==i)
  3. ValueError: list.remove(x): x not in list

The expected output is

  1. [[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]

答案1

得分: 2

  1. 你需要移除一个元素 `i`但不移除条件 `A[i]==i`
  2. for i in range(len(A)):
  3. A[i].remove(i)
英文:

You need to remove an item i but not the condition A[i]==i:

  1. for i in range(len(A)):
  2. A[i].remove(i)

答案2

得分: 1

更好的方法是枚举你的列表。还要确保你要删除的值实际上存在。使用try/except来处理这种情况

  1. A = [[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
  2. for i, e in enumerate(A):
  3. try:
  4. e.remove(i)
  5. except ValueError:
  6. pass
  7. print(A)

输出:

  1. [[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

  1. A = [[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]
  2. for i, e in enumerate(A):
  3. try:
  4. e.remove(i)
  5. except ValueError:
  6. pass
  7. print(A)

Output:

  1. [[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:

确定