我试图了解以下 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}
我可以看到它将 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}
来自文档:
If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
我不是一个足够的数学家,无法完全理解这告诉我的是什么;或者为什么输出的顺序有时会交换。
请您参考如下方法:
一个set是一种无序数据类型 - 它将删除您的重复项。 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]
