最优列表理解(过滤现有列表)

Optimal List Comprehension (Filtering Existing List)

我有一个很大的列表(1e8+ 个条目),格式为 [index:boolean]。我想找到 True 值的索引。 在这个任务中的表现是最重要的。

目前,根据我在 Python 3.7.2 中了解到的情况,执行此操作的最佳方法是使用如下列表推导式:

return [i for i, j in enumerate(numbers) if j]

我还尝试了以下方法(尽管它似乎只是 Python 早期版本的首选方法):

return list(filter(lambda a: a, numbers))

第二种方法比第一种方法慢大约 25%。

目前,此操作大约需要 (0.8*x) 时间,而我算法的实际逻辑部分需要 'x' 时间。 (例如,如果逻辑需要 10 秒,从列表中提取正值大约需要 8 秒)。我本来希望这个操作会快得多。

Performance in this task is of the utmost importance

那么你应该考虑使用 numpy 数组:

import numpy as np
from random import choice
from timeit import Timer

bools = True, False
li = [choice(bools) for _ in range(int(1e8))]
arr = np.array(li)  

print(Timer(lambda: np.nonzero(arr)).repeat(1, 1))

产出

[0.4524359999999916]

那是 0.4524359999999916 秒。