如何删除给定索引集的列表元素?

时间:2019-07-18 16:07:05

标签: python

是否有解决以下问题的有效方法:

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

#result
lst = [2,4]

我的解决方案

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]])

4 个答案:

答案 0 :(得分:2)

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)

打印:

[2, 4]

答案 1 :(得分:2)

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]

答案 2 :(得分:1)

为了基于索引lstindexes_to_remove中删除某些项目,您可以按照相反的顺序对indexes_to_remove中的元素进行排序,然后将其从中删除。 lst在for循环中,以这种方式确保要删除的每个新索引都比以前的索引低,因此列表大小的更改不会影响要删除的新项:

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

输出

[2, 4]

答案 3 :(得分:0)

如果需要考虑速度,请使用numpy模块中的delete函数:

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)

lst = list(range(10000))indexes_to_remove = list(range(0, 2000, 2))的计时测试显示,numpy.delete比列表理解速度快1000倍。

相关问题