示例:
from __future__ import division
import numpy as np
n = 8
"""masking lists"""
lst = range(n)
print lst
# the mask (filter)
msk = [(el>3) and (el<=6) for el in lst]
print msk
# use of the mask
print [lst[i] for i in xrange(len(lst)) if msk[i]]
"""masking arrays"""
ary = np.arange(n)
print ary
# the mask (filter)
msk = (ary>3)&(ary<=6)
print msk
# use of the mask
print ary[msk] # very elegant
结果如下:
>>>
[0, 1, 2, 3, 4, 5, 6, 7]
[False, False, False, False, True, True, True, False]
[4, 5, 6]
[0 1 2 3 4 5 6 7]
[False False False False True True True False]
[4 5 6]
正如您所看到的,对数组进行掩码操作比对列表更加优雅。如果您尝试在列表上使用数组掩码方案,您将会收到一个错误提示:
>>> lst[msk]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: only integer arrays with one element can be converted to an index
这个问题是要找到一种优雅的掩码方式来处理列表。
更新:
jamylak
的答案因为介绍了compress
而被接受,不过Joel Cornett
提到的点让解决方案更加完整并符合我的兴趣。
>>> mlist = MaskableList
>>> mlist(lst)[msk]
>>> [4, 5, 6]
zip()
而不是izip()
。 - Pierrenumpy
,所以突出显示numpy
是很重要的。 - jamylak