How to remove list elements given set of indexes?

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

    In [67]: lst = [1,2,3,4,5]                                                                                                                                                                                                                                                                                                    
    
    In [68]: indexes_to_remove = [0,2,4]                                                                                                                                                                                                                                                                                          
    
    In [69]: for i in sorted(indexes_to_remove, reverse=True): lst.pop(i)                                                                                                                                                                                                                                                                         
    
    In [70]: lst                                                                                                                                                                                                                                                                                                                  
    Out[70]: [2, 4]
    

提交回复
热议问题