len() of unsized object问题求解

下面程序出现“len() of unsized object”错误,不清楚原因,寻求帮助


import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
r=3
length=np.linspace(0,2*np.pi,20)
x=r*np.sin(length)
y=r*np.cos(length)
z=np.outer(np.arange(0,20),np.ones(20))
print(x.shape,y.shape,z.shape)
n=len(x)
s=np.ones((n-1,n-1,n-1),dtype=bool)
fig=plt.figure()
ax=fig.gca(projection='3d')
ax.voxels(x,y,z,s,
         facecolors='r',
         edgecolors='b')
plt.show()

len函数你想计算什么啊?x是什么类型,是一个浮点数吧

仅供参考:
该错误通常发生在尝试在未定义大小的对象上调用 len() 函数时。在这种情况下,您的代码似乎出现错误是因为您在这行代码中尝试对 x 和 y 调用 shape 函数:

print(x.shape, y.shape, z.shape)

然而,当您使用 numpy.linspace 函数创建 length 数组时,您使用了默认值 endpoint=True。这意味着 length 数组中包含了 20 个值,包括 2*np.pi。因此,x 和 y 数组中包含 20 个元素,而 z 数组包含 20 行。但在这种情况下,您希望 x,y 和 z 数组具有相同的形状。

一种解决方法是在 np.sin 和 np.cos 函数调用中使用 length[:-1] 切片,以使 x 和 y 变成 19 个元素的数组。同时,您需要相应地更改 z 数组,以使其成为 19 行。下面是更改后的代码:

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
r = 3
length = np.linspace(0, 2*np.pi, 20)
x = r * np.sin(length[:-1])
y = r * np.cos(length[:-1])
z = np.outer(np.arange(0, 19), np.ones(20))
print(x.shape, y.shape, z.shape)
n = len(x)
s = np.ones((n-1, n-1, n-1), dtype=bool)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x, y, z, s, facecolors='r', edgecolors='b')
plt.show()

在这个版本的代码中,x 和 y 数组现在具有 19 个元素,而 z 数组有 19 行和 20 列。通过这些更改,您应该可以成功运行您的代码并绘制一个三维图形。