How to remove list elements given set of indexes?

前端 未结 4 1977
孤城傲影
孤城傲影 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:34

    If speed is of concern, use delete function from numpy module:

    import numpy as np
    
    lst = [1,2,3,4,5]
    indexes_to_remove = [0,2,4]
    
    lst = np.array(lst)
    indexes_to_remove = np.array(indexes_to_remove)
    
    lst = np.delete(lst, indexes_to_remove)
    

    Timing test for lst = list(range(10000)) and indexes_to_remove = list(range(0, 2000, 2)) shows numpy.delete is about 1000X faster than list comprehension.

提交回复
热议问题