我正在使用Python中的函数计算向量范数。calculate_vector_norm
接收作为元组的向量,并返回包含该向量的范数的浮点值。
import numpy as np
def calculate_norm_vector(vector):
"""
Function that calculates the norm of a vector
Args:
- vector (tuple): the vector used to calculate the norm.
return:
float containing the norm of the vector.
"""
ret=np.zeros(vector.shape[1])
for i in range(vector.shape[1]):
ret[i]=np.linalg.norm(vector[:,i])
return ret
当我使用执行此操作时
calculate_norm_vector((2, -2, 3, -4))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-810f2e17d3ce> in <module>()
----> 1 calculate_norm_vector((2, -2, 3, -4))
<ipython-input-4-5ec67b4c4513> in calculate_norm_vector(vector)
9 float containing the norm of the vector.
10 """
---> 11 ret=np.zeros(vector.shape[1])
12 for i in range(vector.shape[1]):
13 ret[i]=np.linalg.norm(vector[:,i])
AttributeError: 'tuple' object has no attribute 'shape'
您应该使用
len(vector)
而不是
vector.shape[]
bc,元组没有属性形状,因为您的输入是1d元组,所以您可以简单地获得长度。
添加到另一个答案中,您还可以创建一个numpy数组
calculate_norm_vector(np.array([2, -2, 3, -4]))