在 python 中逐项划分(划分 termino a termino en python )

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1785005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:03:29  来源:igfitidea点击:

term by term division in python (division termino a termino en python )

python

提问by ricardo

hello all,need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,

大家好,需要定义一个函数,该函数可以按项矩阵划分,或者在最坏的情况下,在列表数组之间进行划分,以便在第三个矩阵中得到结果,

thanks for any response

感谢您的任何回应

回答by Stephan202

Unless I'm misunderstanding, this is where numpycan be put to good use:

除非我误解了,否则numpy可以很好地利用这里:

>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3])
>>> a / b
array([[  2.,   4.,   6.],
       [  8.,  10.,  12.],
       [ 14.,  16.,  18.]])

This works for multiplication too. And indeed, as noted by Mark, scalar division (and multiplication) is also possible:

这也适用于乘法。事实上,正如Mark所指出的,标量除法(和乘法)也是可能的:

>>> a / 10.0
array([[ 0.1,  0.2,  0.3],
       [ 0.4,  0.5,  0.6],
       [ 0.7,  0.8,  0.9]])
>>> a * 10
array([[10, 20, 30],
       [40, 50, 60],
       [70, 80, 90]])


Edit: to be complete, for lists of lists you could do the following:

编辑:要完整,对于列表列表,您可以执行以下操作:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = [[0.5] * 3, [0.5] * 3, [0.5] * 3]
>>> def mat_div(a, b): 
...     return [[n / d for n, d in zip(ra, rb)] for ra, rb in zip(a, b)] 
... 
>>> mat_div(a, b)
[[2.0, 4.0, 6.0], [8.0, 10.0, 12.0], [14.0, 16.0, 18.0]]