我创建了一个函数来计算每两个位置的距离。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```
range(N)
只返回一个索引序列。如果要同时对行和列进行迭代,可以使用嵌套循环。
len(str(x))
应该只是len(x)
,因为x
和y
应该是坐标列表。
初始化a
时,需要使用列表理解,而不是将[0]*N
乘以N
。后者将使所有行引用同一列表。
def calculate_distances(x,y):
N=len(x)
a=[[0]*N for _ in range(N)]
for i in range(N):
for j in range(N):
a[i][j]=np.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
return a