[英]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 的相应元素。
values[position[0]]
, that is 6
, then the resultant values
array will also change to [2, 1]
.values[position[0]]
,即6
,然后结果values
数组也将更改为[2, 1]
。values[position[1]]
, that is 2
, and the resultant values
array will become [1]
.values[position[1]]
,即2
,结果values
数组将变为[1]
。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.