Python 如何删除给定索引集的列表元素?
是否有有效的方法解决以下问题:Python 如何删除给定索引集的列表元素?,python,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_r
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]])
印刷品:
[2, 4]
印刷品:
[2, 4]
为了根据索引列表从
lst
中删除某些项,您可以按相反顺序对索引中的元素进行排序,然后在for循环中将它们从lst
中删除,以这种方式确保要删除的每个新索引都低于以前的索引,因此列表大小的更改不会影响要删除的新项目:
for i in sorted(indexes_to_remove, reverse=True):
del lst[i]
输出
为了根据索引列表从lst
中删除某些项,您可以按相反顺序对索引中的元素进行排序,然后在for循环中将它们从lst
中删除,以这种方式确保要删除的每个新索引都低于以前的索引,因此列表大小的更改不会影响要删除的新项目:
for i in sorted(indexes_to_remove, reverse=True):
del lst[i]
输出
如果涉及速度,请使用numpy
模块中的功能:
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(范围(10000))
和index\u to\u remove=list(范围(0,2000,2))
的定时测试显示numpy。删除约比列表理解快1000倍。如果需要考虑速度,请使用numpy
模块中的函数:
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(范围(10000))
和index\u to\u remove=list(范围(0,2000,2))
的计时测试显示numpy.delete
比列表理解快约1000倍。解决这类问题的最佳方法是创建一个新的列表,而不是只包含要保留的项[el for i,el in enumerate](lst)如果我不在索引中,那么最好的解决方法就是创建一个新的列表,其中只包含你想保留的项目。[el for i,el in enumerate(lst)如果我不在索引中,那么就删除它]
你应该对索引进行排序,以确保索引索引可以删除[:-1]
是按降序排列的。实际上,在此处反向排序以确保索引按降序排列@niekas更安全。您应该对索引进行排序以移除以确保索引索引以移除[:-1]
是按降序排列的。事实上,在这里反向排序以确保索引按降序排列更安全@niekasu如果解决方案创建了一个新列表,问题是如何从现有列表中删除元素。如果列表很大,您的方法将不起作用。如果解决方案创建了一个新列表,问题是如何从现有列表中删除元素。如果清单太多,你的方法就行不通了。