简体   繁体   English

python 根据另一个列表中的索引从一个列表中删除元素

[英]python remove elements from one list based on indices from another list

I have 2 lists.我有 2 个清单。 First list is a list of values, values , second list is a list of indices, position .第一个列表是值列表values ,第二个列表是索引列表position

position = [1, 0 ,0 ]
values = [2, 6, 1]

output: [6, 2, 1]

what i want to do is, iterate the position list and remove the corresponding element at that position in the values list.我想要做的是,迭代position列表并删除values列表中 position 的相应元素。

  • So, in first pass, it will remove values[position[0]] , that is 6 , then the resultant values array will also change to [2, 1] .因此,在第一遍中,它将删除values[position[0]] ,即6 ,然后结果values数组也将更改为[2, 1]
  • In the second pass, it will remove values[position[1]] , that is 2 , and the resultant values array will become [1] .在第二遍中,它将删除values[position[1]] ,即2 ,结果values数组将变为[1]
  • Lastly it will remove 1 .最后它将删除1

This is my code in O(n**2).这是我在 O(n**2) 中的代码。 Any optimization is appreciated.任何优化表示赞赏。 Thanks!谢谢!

position = [1, 0 ,0 ]
values = [2, 6, 1]
for i in range(len(position)):
    while len(values) > 0:
        x = values[position[i]]
        print(x)
        values.remove(x)
        break

First note: your while loop is useless, as you break at first iteration.首先注意:您的 while 循环是无用的,因为您在第一次迭代时中断。 Your loop is strictly equivalent to您的循环严格等同于

for i in range(len(position)):
    x = values[position[i]]
    print(x)
    values.remove(x)

Then: iterate over values and not indices for position , and use list.pop to get and remove at the same time然后:遍历position的值而不是索引,并同时使用list.pop获取和删除

result = []
for pos in position:
    result.append(values.pop(pos))
print(result)  # [6, 2, 1]

To do that, you can use the .pop() method.为此,您可以使用.pop()方法。

position = [1, 0 ,0 ]
values = [2, 6, 1]

for idx in position:
    values.pop(idx)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM