迭代坐标数组时出错:“TypeError:'float'object is not iterable”(python)

2024-07-05 09:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序应该计算最近的一对的距离。它接受两个已排序的数组:xpts是一个按x坐标排序的对/坐标数组。ypts是一个按y坐标排序的数组。我尝试使用一种分而治之的技术,所以我递归地传入数组的一半。但是,我得到一个错误。在

TypeError: 'float' object is not iterable:  a1, pair1= closest_pair(xlft,ylft)

我的代码是:

def closest_pair(xpts,ypts):
  if xpts size < = 3: 
   if xsize==1:
        return xpts[0][0]
    elif xsize==2:
        return dist(xpts[0],xpts[1])
    else:
        one= xpts[0]
        two= xpts[1]
        three= xpts[2]
        s1= dist(one,two)
        s2= dist(two,three)
        s3= dist(one,three)
        s= (min(s1,s2,s3),min(xpts[0],xpts[1],xpts[2]))
    return s
  else:
   ...
    xlft= xpts[:xsize/2]
    xrht= xpts[(xsize/2)+1:]
    ylft= []
    yrht= []
    median= xpts[(xsize/2)-1][0]


    for p in ypts:
        if p[0] <= median:
            ylft.append(p)
        else:
            yrht.append(p)

    a1, pair1= closest_pair(xlft,ylft)
    a2, pair2= closest_pair(xrht,yrht)
    st= []
    if a1 < a2:
        a3, pair3= (a1,pair1)

    else:
        a3, pair3= (a2,pair2)

        for p in ypts:
            if  abs(p[0]-median) < a3:
                st.append(p)

                n_st= len(st)
                closest= (a3,pair3)
                if n_st>1:
                    for i in range(n_st-1):
                        for j in range(i+1,min(i+8,n_st)):
                            if dist(st[i],st[j]) < closest[0]:
                                closest= (dist(st[i],st[j]),(st[i],st[j]))
        d= closest
        return d


d1 = closest_pair(xpts, ypts)[0]
print d1

Tags: inforreturnifdista1数组else
2条回答
if xsize==1:
        return xpts[0][0]

你在这里还一个浮子。这就是导致错误的原因。在

假设您有一个坐标元组的列表,并将其索引到该列表中,然后该元组给您一个float,它不能被迭代。因此,信息。在

closest_pair返回一个float,因此

a1, pair1= closest_pair(xlft,ylft)

将导致异常。这称为序列解包,并尝试迭代closest_pair(xlft,ylft)的值

回溯包括异常的行号。如果您可以包含一个与抛出异常的行相对应的标记(例如#<== exception here),这将非常有帮助

相关问题 更多 >