在Python中根据另一个列表的情况删除一个列表的元素

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

Removing elements of one list wth respect to the other in Python

问题

  1. I have lists ```J``` and ```Indices```. I want to remove elements of ```J``` according to locations specified in ```Indices```. For example, ```Indices[0]=1``` and ```Indices[1]=2```. This means that ```J[0][1]``` and ```J[0][2]``` should be removed in one go. But I am getting an error. I present the expected output.
  2. Indices=[1,2]
  3. J=[[2, 3, 6, 7, 9, 10]]
  4. J=J[0].remove(Indices[0])
  5. print(J)

The error is

  1. in <module>
  2. J=J[0].remove(Indices[0])
  3. ValueError: list.remove(x): x not in list

The expected output is

  1. [[2, 7, 9, 10]]
英文:

I have lists J and Indices. I want to remove elements of J according to locations specified in Indices. For example, Indices[0]=1 and Indices[1]=2. This means that J[0][1] and J[0][2] should be removed in one go. But I am getting an error. I present the expected output.

  1. Indices=[1,2]
  2. J=[[2, 3, 6, 7, 9, 10]]
  3. J=J[0].remove(Indices[0])
  4. print(J)

The error is

  1. in <module>
  2. J=J[0].remove(Indices[0])
  3. ValueError: list.remove(x): x not in list

The expected output is

  1. [[2, 7, 9, 10]]

答案1

得分: 2

  1. 使用这个

Indices = [1, 2]
J = [[2, 3, 6, 7, 9, 10]]

for index in sorted(Indices, reverse=True):
J[0].pop(index)

print(J)

  1. `remove`: 移除传递给它的元素,如果元素不在列表中,则报错。
  2. `pop`: 移除传递给它的索引处的元素,如果没有提供索引,则将移除最后一个元素([-1]索引),如果索引不正确,则报错。
英文:

Use this

  1. Indices = [1, 2]
  2. J = [[2, 3, 6, 7, 9, 10]]
  3. for index in sorted(Indices, reverse=True):
  4. J[0].pop(index)
  5. print(J)

remove: remove the element that is passed in it, error if the element is not in the list.

pop: remove the element on the index that is passed in it, if no index provide then it will remove the last element[-1 index], if the index is not correct then error.

huangapple
  • 本文由 发表于 2023年6月15日 16:06:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480366.html
匿名

发表评论

匿名网友

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

确定