[英]Python: Removing elements from list by index based on elements in another list
So I have a list所以我有一个清单
a_list = [0,3,4,7,9,11,15]
and a list of outliers和异常值列表
outliers = [0,3,4]
The outliers is the list of indexes that need to be removed from a_list异常值是需要从 a_list 中删除的索引列表
So in this case, remove the elements in index 0, 3, 4 from a_list.所以在这种情况下,从 a_list 中删除索引 0、3、4 中的元素。 Result should be:
结果应该是:
remove these = [0,7,9]
a_list = [0,3,4,11,15]
If I use the del method, the index will change so once I remove 0th index, I will still remove the 3rd index but instead remove 9 and 4th index will remove 15.如果我使用 del 方法,索引会改变,所以一旦我删除第 0 个索引,我仍然会删除第 3 个索引,但是删除 9 和第 4 个索引将删除 15。
How can I remove items from a_list with the indexes specified in a separate list?如何使用单独列表中指定的索引从 a_list 中删除项目?
Compare index to outliers
list.将索引与
outliers
列表进行比较。 If the index
is matching to outliers
then skip it.如果
index
与outliers
匹配,则跳过它。
print([x for i, x in enumerate(a_list) if i not in outliers])
Better to use set(outliers)
if outliers contain the duplicate elements.如果异常值包含重复元素,最好使用
set(outliers)
。
Here is a real quick implementation based on what the others were commenting about.这是基于其他人评论的真正快速实施。
a_list = [0,3,4,7,9,11,15]
outliers = [0,3,4]
outliers.reverse()
for i in outliers:
del a_list[i]
print(a_list)
Simply call outliers.reverse()
before iterating and delete as normal.只需在迭代之前调用
outliers.reverse()
并照常删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.