Python: Elegant and efficient ways to mask a list

后端 未结 5 1353
情深已故
情深已故 2020-12-05 14:26

Example:

from __future__ import division
import numpy as np

n = 8
\"\"\"masking lists\"\"\"
lst = range(n)
print lst

# the mask (filter)         


        
5条回答
  •  自闭症患者
    2020-12-05 14:43

    Since jamylak already answered the question with a practical answer, here is my example of a list with builtin masking support (totally unnecessary, btw):

    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))
    

    Usage:

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

    Note that compress stops when either the data or the mask runs out. If you wish to keep the portion of the list that extends past the length of the mask, you could try something like:

    from itertools import izip_longest
    
    [i[0] for i in izip_longest(myList, mask[:len(myList)], fillvalue=True) if i[1]]
    

提交回复
热议问题