如何解决不匹配数组和列表相乘的广播问题



我试图将标量列表与数组相乘,但遇到了广播错误。

什么是解决这个问题的蟒蛇方法,并获得三个不同的数组,每个数组按每个lst的数量缩放?

import numpy as np
ar = np.array([2, 3, 1, 0,5,6,9,20,10,15,1,54,20,10,40,50,60, 49,2,40]).reshape(10,2)
scale = 2
lst = [4,5,6]
lst *  ar
Out: ValueError: operands could not be broadcast together with shapes (3,) (10,2)

IIUC:试试这个:

arrs = [ar * scalar for scalar in lst]
print(arrs[0])
print(arrs[1])
print(arrs[2])

输出:

array([[  8,  12],
[  4,   0],
[ 20,  24],
[ 36,  80],
[ 40,  60],
[  4, 216],
[ 80,  40],
[160, 200],
[240, 196],
[  8, 160]])
array([[ 10,  15],
[  5,   0],
[ 25,  30],
[ 45, 100],
[ 50,  75],
[  5, 270],
[100,  50],
[200, 250],
[300, 245],
[ 10, 200]])
array([[ 12,  18],
[  6,   0],
[ 30,  36],
[ 54, 120],
[ 60,  90],
[  6, 324],
[120,  60],
[240, 300],
[360, 294],
[ 12, 240]])

我会选择以下内容:

ar[None, :, :] * np.array(lst)[:,None,None]
array([[[  8,  12],
[  4,   0],
[ 20,  24],
[ 36,  80],
[ 40,  60],
[  4, 216],
[ 80,  40],
[160, 200],
[240, 196],
[  8, 160]],
[[ 10,  15],
[  5,   0],
[ 25,  30],
[ 45, 100],
[ 50,  75],
[  5, 270],
[100,  50],
[200, 250],
[300, 245],
[ 10, 200]],
[[ 12,  18],
[  6,   0],
[ 30,  36],
[ 54, 120],
[ 60,  90],
[  6, 324],
[120,  60],
[240, 300],
[360, 294],
[ 12, 240]]])

相关内容

  • 没有找到相关文章