## 在一个numpy数组中相乘内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (194)

``````[1,2,3]   [0]
[4,5,6] * [1]
[7,8,9]   [2]
``````

``````[0,0,0]
[4,5,6]
[14,16,18]
``````

``````[0,2,6]
[0,5,12]
[0,8,18]
``````

### 2 个回答

``````a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)
``````

``````A * b[:, None]
``````

（或`(A.T * b).T`）因为它很短。

``````import numpy
import perfplot

def newaxis(data):
A, b = data
return A * b[:, numpy.newaxis]

def none(data):
A, b = data
return A * b[:, None]

def double_transpose(data):
A, b = data
return (A.T * b).T

def double_transpose_contiguous(data):
A, b = data
return numpy.ascontiguousarray((A.T * b).T)

def diag_dot(data):
A, b = data
return numpy.dot(numpy.diag(b), A)

def einsum(data):
A, b = data
return numpy.einsum("ij,i->ij", A, b)

perfplot.save(
"p.png",
setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
kernels=[
newaxis,
none,
double_transpose,
double_transpose_contiguous,
diag_dot,
einsum,
],
n_range=[2 ** k for k in range(14)],
logx=True,
logy=True,
xlabel="len(A), len(b)",
)
``````