例:
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
問題は、s のエレガントなマスキングを見つけることlist
です。
更新:
の回答jamylak
は紹介のために受け入れられましたが、がcompress
言及した点によりJoel Cornett
、ソリューションは私の興味のある形に完全なものになりました。
>>> mlist = MaskableList
>>> mlist(lst)[msk]
>>> [4, 5, 6]