如何对带有任意嵌套的两个形状相同的列表执行逐元素的算术运算(例如加,减,乘) [英] How to perform element-wise arithmetic operations (e.g. add, subtract, multiply) of two equally shaped lists with arbitrary nestings

查看:58
本文介绍了如何对带有任意嵌套的两个形状相同的列表执行逐元素的算术运算(例如加,减,乘)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两个包含数字或多个嵌套列表的Python列表上执行逐元素的数学运算(例如,求和,乘..).

I want to perform element-wise mathematical operations (e.g. sum, multiply..) on two Python lists containing numbers or multiple nested lists which may contain again numbers or lists and so on.

执行操作时,两个列表的形状相同.此外,结果的形状应与两个输入列表相同.

The shapes of the two lists are equal when performing the operation. Furthermore, the result should be of the same shape as the two input lists.

形状可能有所不同:

  1. 长度

宽度(即嵌套数)

顺序(例如,列表以数字开头,后跟嵌套列表,但也可能是它以嵌套列表开头,后跟数字).

order (e.g. the lists start with a number followed by a nested list, but it may also be that it starts with a nested list, followed by numbers).

每次我要执行数学运算时,形状都会任意改变.

The shape changes arbitrarily each time I want to perform a mathematical operation.

如何在任意形状的列表上执行数学运算?

How can I perform math operations on arbitrarily shaped lists?

过去,我为每种不同的形状实现了自定义代码段,类似于 4 5 6 7中减去2个列表,8 , 9 的每个元素的乘积,但是我想知道是否已经有一个更通用的解决方案,例如库或参考代码.

In the past, I've implemented a customized piece of code for each different shape, similar to 1, 2, 3, 4, 5, 6, 7, 8, 9, but I was wondering if there is already a more general solution in the form of a library or reference code for this.

示例1 (求和):

a = [ 1, 2, 3, 4,[ 5, 6, 7, 8]]
b = [10,20,30,40,[50,60,70,80]]
c = elementwiseSUM(a,b)
c

会导致

[11, 22, 33, 44, [55, 66, 77, 88]]

示例2 (求和):

d = [ 1,[ 2, 3],  4, [ 5, 6, 7], [[ 8], [ 9, 10]]]
e = [10,[20,30], 40, [50,60,70], [[80], [90,100]]]
f = elementwiseSUM(d,e)
f

会导致

[11, [22, 33], 44, [55, 66, 77], [[88], [99, 110]]]

示例3 (乘法):

g = [[4,2],1,1]
h = [[8,3],1,9]
i = elementwiseMUL(g,h)
i

会导致

[[32, 6], 1, 9]

elementwiseSUM() elementwiseMUL()是我正在寻找的库函数的占位符.

elementwiseSUM() and elementwiseMUL() are placeholders for the library functions which I am looking for.

推荐答案

这是我想出的解决方案

a = [ 1,  2,  3,  4, [ 5,  6,  7,  8]]
b = [10, 20, 30, 40, [50, 60, 70, 80]]

def element_wise(a, b, f):
    return [element_wise(i, j, f) if type(i) == list and type(j) == list else f(i, j) for i, j in zip(a, b)]

c = element_wise(a, b, lambda x, y: x + y) # [11, 22, 33, 44, [55, 66, 77, 88]]

所以 a b 是您的列表,而 f 是要应用的函数,如您所见,我写了一个简单的添加整数的功能

so a and b are your lists, and f is the function you want to apply, as you can see I wrote a simple function to add ints

您可以编写自己的lambda,也可以只使用 operator 模块.

You can either write your own lambdas or just use the operator module.

这篇关于如何对带有任意嵌套的两个形状相同的列表执行逐元素的算术运算(例如加,减,乘)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆