gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:19 25 4
gpt4 key购买 nike

我创建了一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com