在python3.7中将两个数组相乘

数据挖掘 Python 麻木的
2022-03-14 09:15:15

我正在尝试使用以下语法使用 numpy 将 python 3.7 中的两个数组相乘:

array1 = np.array([{1,2,3,4},{5,6,7,8}]) 
print (array1)  
array2=array1*array1 
print(array2)  

但是出现了这个错误

TypeError: unsupported operand type(s) for *: 'set' and 'set'
1个回答

您只是在定义您的数组,以便它由 python 组成set这是一种不同的数据结构,与数组不同,它不能相乘。

只需将您的代码更改为:

array1 = np.array([[1,2,3,4],[5,6,7,8]])

唯一的区别是使用方括号而不是大括号。这些是 pythonlist对象(或标准数组)。

array2=array1*array1  
print(array2)

[[ 1  4  9 16]
 [25 36 49 64]]