首页 > 解决方案 > 一维和二维数组上的 numpy 点

问题描述

我试图了解以下 python 代码中发生的情况:

import numpy as np

numberList1 = [1,2,3]
numberList2 = [[4,5,6],[7,8,9]]

result = np.dot(numberList2, numberList1)

# Converting iterator to set
resultSet = set(result)
print(resultSet)

输出:

{32, 50}

我可以看到它正在将每个元素乘以 -so内numberList1每个数组中相同位置的元素。numberList2{1*4 + 2*5 + 3*6 = 32},{1*7+2*8+3*9 = 50}

但是,如果我将数组更改为:

numberList1 = [1,1,1]
numberList2 = [[2,2,2],[3,3,3]]

然后我看到的输出是

{9, 6}

这是错误的方法...

并且,如果我将其更改为:

numberList1 = [1,1,1]
numberList2 = [[2,2,2],[2,2,2]]

然后我看到的输出就是

{6}

从文档中:

如果 a 是 ND 数组且 b 是一维数组,则它是 a 和 b 的最后一个轴上的和积。

我还不够数学家,无法完全理解这告诉我什么;或者为什么有时输出的顺序会互换。

标签: pythonarraysnumpydot-product

解决方案


aset是一种无序的数据类型 - 它会删除您的重复项。np.dot不返回迭代器(如您的代码中所述),但np.ndarray将按照您期望的顺序返回:

import numpy as np

numberList1 = [1, 2, 3]
numberList2 = [[4, 5, 6], [7, 8, 9]]

result = np.dot(numberList2, numberList1)
# [32 50]
# <class 'numpy.ndarray'>

# numberList1 = [1, 1, 1]
# numberList2 = [[2, 2, 2], [3, 3, 3]]
# -> [6 9]

推荐阅读