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.
values[position[0]]
, that is 6
, then the resultant values
array will also change to [2, 1]
.values[position[1]]
, that is 2
, and the resultant values
array will become [1]
.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.