【发布时间】:2018-05-27 08:35:15
【问题描述】:
我创建了一个 2D 列表,并在 the same type question 后面的 2D 列表上应用了蒙版。事实证明,发布的解决方案根本不适用于 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 列表。
【问题讨论】:
-
那是因为
compress作用于列表的项目,而不是子列表的项目。所以一切都是真实的。
标签: python python-3.x