How to remove list elements given set of indexes?

前端 未结 4 1976
孤城傲影
孤城傲影 2021-01-24 06:16

Is there an efficient way to solve the following problem:

lst = [1,2,3,4,5]
indexes_to_remove = [0,2,4]

#result
lst = [2,4]

My solution

<
4条回答
  •  无人及你
    2021-01-24 06:50

    In order to remove certain items from lst based on a list of indices indexes_to_remove, what you can do is sort the elements in indexes_to_remove in reverse order, and then remove them from lst in a for loop, ensuring in this way that each new index to remove is lower than the previous and hence the change in size of the list won't affect the new items to remove:

    for i in sorted(indexes_to_remove, reverse=True):
        del lst[i] 
    

    Output

    [2, 4]
    

提交回复
热议问题