通过reduce逐元素添加两个3d列表



我有一个数组,其中包含a[0]a[1]2d数组和a[2]1d数组。我想通过reduce()map()的结果与下一行聚合,但由于数组a的形式,我发现尝试 numpy 有些困难。

例如:

a = [((1,6), (4,7), (4,5)), ((3,7), (8,2), (2,4)), (2,4,5)]
b = [((3,7), (8,2), (2,4)), ((6,5), (1,7), (4,8)), (7,2,1)] 
result = [((4,13), (12,9), (6,9)), ((9,12), (9,9), (6,12)), (9,6,6)]

如何在 python 中执行此操作?

我必须想出这个丑陋的列表理解的东西,但这至少可以工作:

result = [tuple([tuple(row) if not isinstance(row, np.int64) else row for row in np.array(aa)+np.array(bb)]) for aa, bb in zip(a, b)]
a
Out[29]: [((1, 6), (4, 7), (4, 5)), ((3, 7), (8, 2), (2, 4)), (2, 4, 5)]
b
Out[30]: [((3, 7), (8, 2), (2, 4)), ((6, 5), (1, 7), (4, 8)), (7, 2, 1)]
result
Out[31]: [((4, 13), (12, 9), (6, 9)), ((9, 12), (9, 9), (6, 12)), (9, 6, 6)]

您可能需要将np.int64事物调整为默认的numpy int类型。

我认为,在此使用map和lambda函数可以使它稍微好一点。

result = [tuple(map(lambda x: x if isinstance(x, np.int64) else tuple(x), np.array(aa)+np.array(bb))) for aa, bb in zip(a, b)]

此解决方案实现了zipmap的一些朴素递归嵌套版本:

def nested_map(fnc, it):
try: 
return type(it)(nested_map(fnc, sub) for sub in it)
except TypeError:
return fnc(it)
def nested_zip(*iterables):
r = []
for x in zip(*iterables):
try:
r.append(type(x[0])(nested_zip(*x)))
except TypeError:
r.append(x)
return r
nested_map(sum, nested_zip(a, b))
# [((4, 13), (12, 9), (6, 9)), ((9, 12), (9, 9), (6, 12)), (9, 6, 6)]

此实现具有适用于任意嵌套级别的附加灵活性:

nested_map(sum, nested_zip([(1, 2), 3, [4]], [(1, 2), 3, [4]]))
# [(2, 4), 6, [8]]

最新更新