简体   繁体   中英

python remove elements from one list based on indices from another list

I have 2 lists. First list is a list of values, values , second list is a list of indices, 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.

  • So, in first pass, it will remove values[position[0]] , that is 6 , then the resultant values array will also change to [2, 1] .
  • In the second pass, it will remove values[position[1]] , that is 2 , and the resultant values array will become [1] .
  • Lastly it will remove 1 .

This is my code in 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. 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

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

To do that, you can use the .pop() method.

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

for idx in position:
    values.pop(idx)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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