[英]Show Math Addition in two Arrays Python
我如何编写代码来显示两个 arrays 之间的加法运算(按行),我不想要加法的结果,但想说明操作。 这是我所拥有的,但是我的代码没有给我正确的 output
import numpy as np
Grid = np.random.randint(-50,50, size=(5,4))
iList =np.array([[1, -1, 2, -2]])
result = (Grid.astype(str), iList.astype(str))
print(result)
output 需要达到这个效果
([3+1 4-1 4+2 5-2] [6+1 9-1 7+2 8-2]
等等
谢谢你。
您基本上想将 function 应用到两个不同大小的 numpy arrays 上,利用 numpy 的广播能力。
这有效:
import numpy as np
grid = np.random.randint(-50, 50, size=(5, 4))
i_list = np.array([[1, -1, 2, -2]])
def sum_text(x: int, y: int):
return f'{x}+{y}'
# create a ufunc, telling numpy that it takes 2 arguments and returns 1 value
np_sum_text = np.frompyfunc(sum_text, 2, 1)
result = np_sum_text(grid, i_list)
print(result)
结果:
[['46+1' '-27+-1' '35+2' '-3+-2']
['-5+1' '6+-1' '2+2' '22+-2']
['6+1' '-45+-1' '-21+2' '31+-2']
['25+1' '-4+-1' '-24+2' '3+-2']
['-32+1' '-10+-1' '-19+2' '28+-2']]
或者,也许您不需要重用 function 之类的单行代码:
print(np.frompyfunc(lambda x, y: f'{x}+{y}', 2, 1)(grid, i_list))
在负 integer 之前摆脱+
是微不足道的:
def sum_text(x: int, y: int):
return f'{x}+{y}' if y >= 0 else f'{x}{y}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.