这是我的第一种方法。
def remove_indices(numbers, indices):
indices = set(indices)
return [x for i, x in enumerate(numbers) if i not in indices]
这是一个测试模块,用于在您指定的条件下对其进行测试。(300 万个元素,需要删除 25 万个元素)
import random
def create_test_set():
numbers = range(3000000)
indices = random.sample(range(3000000), 250000)
return numbers, indices
def remove_indices(numbers, indices):
indices = set(indices)
return [x for i, x in enumerate(numbers) if i not in indices]
if __name__ == '__main__':
import time
numbers, indices = create_test_set()
a = time.time()
numbers = remove_indices(numbers, indices)
b = time.time()
print b - a, len(numbers)
在我的笔记本电脑上大约需要 0.6 秒。如果您要多次使用它,您可以考虑预先设置索引。
(FWIW bradley.ayers 解决方案花费的时间比我愿意等待的时间长。)
编辑:这稍微快一点:(0.55 秒)
def remove_indices(numbers, indices):
return [numbers[i] for i in xrange(len(numbers)) if i not in indices]