简体   繁体   中英

How to remove list elements given set of indexes?

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

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

x = -1
for i in range(len(indexes_to_remove)):
    x+=1
    if i!=0:
        indexes_to_remove[i] = indexes_to_remove[i] - x # because indexes will shift
    lst.remove(lst[indexes_to_remove[i]])
lst = [1,2,3,4,5]
indexes_to_remove = [0,2,4]

lst = [item for i, item in enumerate(lst) if i not in indexes_to_remove]

print(lst)

Prints:

[2, 4]
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]

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] 

[2, 4]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM