【发布时间】:2021-04-07 23:17:30
【问题描述】:
我创建了一个函数来计算每两个地方的距离。 x 和 y 是位置 x s 和 y s 的列表
def calculate_distances(x,y):
N=len(str(x))
a=[[0]*N]*N
for i,j in range(N):
a[i][j]=np.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
return a
我将它应用在讲师提供的片段中。
D = calculate_distances(x,y)
fig = plt.figure(figsize=(6,6));
total_distance = 0
for i in range(n_city-1):
plt.scatter(x,y,marker="s",c="k");
plt.plot([x[i],x[i+1]], [y[i],y[i+1]],
alpha=(i+1)/(n_city),lw=2,color="k");
total_distance += D[i,i+1]
plt.title("Distance traveled = %0.3f" %total_distance)
time.sleep(1.0)
clear_output(wait = True)
display(fig) # Reset display
我收到了错误消息,我粘贴在下面
TypeError Traceback (most recent call last)
<ipython-input-21-3804c182182f> in <module>
3 # We use the calculate_distances function you created above to compute the distance matrix
4 # Make sure you feed in the correct "x" and "y" arrays if you used different variables names
----> 5 D = calculate_distances(x,y)
6
7 fig = plt.figure(figsize=(6,6));
<ipython-input-20-ecc344ee386f> in calculate_distances(x, y)
3 N=len(str(x))
4 a=[[0]*N]*N
----> 5 for i,j in range(N):
6 a[i][j]=np.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
7 return a
TypeError: cannot unpack non-iterable int object```
【问题讨论】:
-
您希望
for i,j in range(N):做什么?range(N)一次只返回一个数字,不能将它分配给两个变量。 -
a=[[0]*N]*N也是错误的。见stackoverflow.com/questions/240178/… -
你需要嵌套循环:
for i in range(N): for j in range(N): ... -
如果
x是位置列表,为什么要使用len(str(x))而不是len(x)? -
我不知道 x 是什么,但是,如果我使用 len(x),它会给我一个错误消息,告诉我不能在 float 上使用 len。
标签: python python-3.x error-handling