如何修复“ TypeError:未调整大小的对象的len()”

Xab*_*ade 7 python arrays numpy

我正进入(状态:

TypeError:len()个未调整大小的对象

运行以下脚本后:

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')
Run Code Online (Sandbox Code Playgroud)

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

Mos*_*oye 9

改用数组的size属性:

nv = v.size
nu = u.size
Run Code Online (Sandbox Code Playgroud)

您可能还想使用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
Run Code Online (Sandbox Code Playgroud)

  • 鉴于他假设向量 `len` 和 `size` 是等价的。但是我投了反对票,因为 `numpy.array` 确实可以与 `len` 一起使用,除非它是一个标量(它会抛出提到的错误)。 (3认同)
  • * Downvoter *想发表评论吗? (2认同)