例子:
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]
如您所见,与列表相比,对数组进行屏蔽的操作更加优雅。如果你尝试使用 list 上的数组掩码方案,你会得到一个错误:
>>> 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
问题是为list
s 找到一个优雅的掩码。
更新:
的答案jamylak
被接受为介绍compress
但是提到的点Joel Cornett
使解决方案完全符合我感兴趣的所需形式。
>>> mlist = MaskableList
>>> mlist(lst)[msk]
>>> [4, 5, 6]