如何在Python中屏蔽2D列表?
我创建了一个二维列表,并在随后的二维列表上应用了一个遮罩。结果证明,发布的解决方案根本不适用于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
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
作用于列表的项目,而不是子列表的项目。所以一切都是真实的。