29

例:

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]
4

6 に答える 6

46

使用している場合numpy:

>>> import numpy as np
>>> a = np.arange(8)
>>> mask = np.array([False, False, False, False, True, True, True, False], dtype=np.bool)
>>> a[mask]
array([4, 5, 6])

あなたが探しているnumpyを使用していない場合itertools.compress

>>> from itertools import compress
>>> a = range(8)
>>> mask = [False, False, False, False, True, True, True, False]
>>> list(compress(a, mask))
[4, 5, 6]
于 2012-04-23T04:28:51.850 に答える
7

jamylak はすでに実用的な回答で質問に答えているので、組み込みのマスキング サポートを使用したリストの例を次に示します (完全に不要です)。

from itertools import compress
class MaskableList(list):
    def __getitem__(self, index):
        try: return super(MaskableList, self).__getitem__(index)
        except TypeError: return MaskableList(compress(self, index))

使用法:

>>> myList = MaskableList(range(10))
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mask = [0, 1, 1, 0]
>>> myList[mask]
[1, 2]

compressデータまたはマスクがなくなると停止することに注意してください。マスクの長さを超えるリストの部分を保持したい場合は、次のようなことを試すことができます。

from itertools import izip_longest

[i[0] for i in izip_longest(myList, mask[:len(myList)], fillvalue=True) if i[1]]
于 2012-04-23T04:54:45.110 に答える
1

以下は、Python 3 で完全に機能します。

np.array(lst)[msk]

結果として返されるリストが必要な場合:

np.array(lst)[msk].tolist()
于 2021-01-21T22:11:59.457 に答える