【问题标题】:TypeError: cannot unpack non-iterable int object . When I tried to attend the len of x, it give me an error msg said it is float, now it is int?TypeError: cannot unpack non-iterable int object 。当我尝试参加 x 的 len 时,它给了我一个错误消息说它是 float,现在它是 int?
【发布时间】: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


【解决方案1】:

range(N) 仅返回单个索引序列。如果要遍历行和列,可以使用嵌套循环。

len(str(x)) 应该只是 len(x),因为 xy 应该是坐标列表。

在初始化a 时,您需要使用列表推导而不是将[0]*NN 相乘。后者将使所有行引用同一个列表。

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

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多