对于更大的数组,使用 NumPy 会更高效:
import numpy as np
my_list = np.array(['a', 'd', 'a', 'd', 'c','e'])
words_2_remove = np.array(['a', 'c'])
mask = np.isin(my_list, words_2_remove, invert=True)
# mask will be [False True False True False True]
loc = np.where(~mask)[0]
print(loc)
>>> [0 2 4]
print(my_list[mask])
>>> ['d' 'd' 'e']
而且得到loc 索引的补码也很容易:
print(np.where(mask)[0])
>>> [1 3 5]
时间安排:
与@Austin 的列表推导版本比较。
对于原始数组:
my_list = np.array(['a', 'd', 'a', 'd', 'c','e'])
words_2_remove = np.array(['a', 'c'])
%%timeit
mask = np.isin(my_list, words_2_remove, invert=True)
loc = np.where(~mask)[0]
>>> 11 µs ± 53.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
my_list =['a', 'd', 'a', 'd', 'c','e']
words_2_remove = ['a', 'c']
%%timeit
loc = [i for i, x in enumerate(my_list) if x in words_2_remove]
res = [x for x in my_list if x not in words_2_remove]
>>> 1.31 µs ± 7.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
对于大数组:
n = 10 ** 3
my_list = np.array(['a', 'd', 'a', 'd', 'c','e'] * n)
words_2_remove = np.array(['a', 'c'])
%%timeit
mask = np.isin(my_list, words_2_remove, invert=True)
loc = np.where(~mask)[0]
>>> 114 µs ± 906 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
my_list =['a', 'd', 'a', 'd', 'c','e'] * n
words_2_remove = ['a', 'c']
%%timeit
loc = [i for i, x in enumerate(my_list) if x in words_2_remove]
res = [x for x in my_list if x not in words_2_remove]
>>> 841 µs ± 677 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
根据用例,您可以选择更适合的。
延伸阅读:
np.isin 上的文档:https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.isin.html
将布尔掩码数组转换为索引:How to turn a boolean array into index array in numpy
np.where 上的文档:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html
有关使用 NumPy 进行索引的更多信息:https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.indexing.html