Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中屏蔽2D列表?_Python_Python 3.x - Fatal编程技术网

如何在Python中屏蔽2D列表?

如何在Python中屏蔽2D列表?,python,python-3.x,Python,Python 3.x,我创建了一个二维列表,并在随后的二维列表上应用了一个遮罩。结果证明,发布的解决方案根本不适用于2D列表。 以下是代码和输出: from itertools import compress class MaskableList(list): def __getitem__(self, index): try: return super(MaskableList, self).__getitem__(index) except TypeError: retur

我创建了一个二维列表,并在随后的二维列表上应用了一个遮罩。结果证明,发布的解决方案根本不适用于2D列表。 以下是代码和输出:

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

aa=[['t', 'v'], ['a', 'b']]
aa=MaskableList(aa)
print(aa)
>>> [['t', 'v'], ['a', 'b']]

mask1=[[1,0],[0,1]]
print(aa[mask1])
>>> [['t', 'v'], ['a', 'b']]

mask2=[1,0,0,1]
print(aa[mask2])
>>> [['t', 'v']]

有一种干净有效的方法可以屏蔽2D列表。

肯定有一种更好的解决方案,它涉及到混淆
类的定义,但解决方法是:

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

aa = [['t', 'v'], ['a', 'b']]
mask1 = [[True, False], [False, True]]

new = [MaskableList(sublist)[submask] for sublist, submask in zip(aa, mask1)]
print(new)  # -> [['t'], ['b']]

一种简单的方法是重新实现
itertools.compress
实现的生成器表达式

将其转换为语句,当数据和选择器都位于给定位置时,在该子列表上递归新的压缩函数:

from collections import Iterable
def compress_rec(data, selectors):
    for d, s in zip(data, selectors): # py3 zip is py2 izip, use itertools.zip_longest if both arrays do not have the same length
        if isinstance(d, Iterable) and isinstance(s, Iterable):
            yield compress_rec(d, s)
        else:
            yield d
这样,它可以与任何维数组一起工作


HTH

这是因为
compress
作用于列表的项目,而不是子列表的项目。所以一切都是真实的。