简体   繁体   English

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

[英]Element-wise add of two 3d lists through reduce

I have an array which contains in a[0] and in a[1] a 2d array and in a[2] a 1d array. 我有一个数组,其中包含a[0]a[1]的2d数组和a[2]一个1d数组。 I want to aggregate the result of the map() with the next line through reduce() but I find some difficulties trying numpy because of the form of array a . 我想通过reduce()map()的结果与下一行进行聚合,但是由于数组a的形式,我发现尝试numpy会遇到一些困难。

for example: 例如:

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)]

How can I do this in python? 如何在python中做到这一点?

I have to come up with this ugly list comprehension thing but this could work at least: 我必须想出这个难看的清单理解问题,但这至少可以起作用:

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)]

You may need to make adjustment on np.int64 thing to your default numpy int type. 您可能需要对np.int64进行调整,以将其设为默认的numpy int类型。

Use map and lambda function in this can make it slightly better I think. 我认为使用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)]

This solution implements some naive recursive nested versions of zip and map : 此解决方案实现了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)]

This implementation has the added flexibility of working for arbitrary nesting levels: 此实现具有处理任意嵌套级别的额外灵活性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM