python - 如何在 Python 中屏蔽二维列表?

标签 python python-3.x

我创建了一个 2D 列表并在 2D 列表上应用了掩码,然后是 the same type question .事实证明,发布的解决方案根本不适用于 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 列表。

最佳答案

一个简单的方法是重新实现 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

关于python - 如何在 Python 中屏蔽二维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47793276/

相关文章:

python - 了解赋值错误之前的引用

python - 用python制作弹跳 turtle

Python:Reduce() 和函数作为函数的参数

python-3.x - 如何根据 Pandas 中的其他列根据另一列中的间隔填充缺失值?

Python字典递归搜索

algorithm - python中后缀算法的中缀

python-3.x - 为什么 flake8 在 lambda 中调用 print 时会抛出语法错误?

python - 在 pytube3 中获取 youtube 视频的标题?

python - 我如何使用 __getitem__ 和 __iter__ 并从字典返回值?

python - 如何在 Tkinter 应用程序上收听终端?