问题

如何修复 “TypeError: len() of unsized object”


我正进入(状态:

TypeError:len() 或 unsized 对象

运行以下脚本后:

from numpy import *

v=array(input('Introduce un vector v: '))
u=array(input('Introduce un vector u: '))

nv= len(v)
nu= len(u)

diferenza= 0; i=0

if nv==nu:

    while i<nv:
        diferenza=diferenza + ((v[i+1]-u[i+1]))**2

    modulo= sqrt(diferenza)
    print('Distancia', v)
else:
    print('Vectores de diferente dimensión')

我怎样才能解决这个问题?

推荐答案

请改用数组的 size 属性:

nv = v.size
nu = u.size

您可能还想使用 numpy.fromstring 将输入字符串转换为数组:

>>> v = np.fromstring(input('enter the elements of the vector separated by comma: '), dtype=int, sep=',')
enter the elements of the vector separated by comma: 1, 2, 3
>>> v
array([1, 2, 3])
>>> len(v)
3
>>> v.size
3