0

我遇到了循环输出数量的问题。

neighbours=[]#this array will hold the distance to the k-th neighbour

for i in range(0, len(selection)-1):#208 values in selection

      n2 =[]#this array will hold the distance to all the other 207 points
      for k in range(0, len(selection)-1):

          d = {}
          if i != k:#to remove the same point being considered
              ra_diff = selection[i]['ra']-selection[k]['ra']
              dec_diff= selection[i]['dec']-selection[k]['dec']
              d=float(math.hypot(ra_diff , dec_diff))#finds the distance
              n2.append(d)  
      n2.sort()
      neighbours.append(n2[6])#passes the 7th value to the array

这是查找 k 最近邻居的代码的一部分。选择有 208 个值,嵌套循环应该计算到所有点的距离并找到到每个点的第 7 个最近点。

迭代后,neighbors 数组仅保存 207 个值(即 len(neighbours)=207),但所有 208 个值应该有第 7 个最近邻。谁能指出问题出在哪里?

4

1 回答 1

1

这一行:

for i in range(0, len(selection)-1):

for k in range(0, len(selection)-1): 

可能是问题,range不包括 stop 参数,因此- 1缺少最后一个元素。

例如。

>>> L = [1, 2, 3]
>>> range(len(L)) # goes from 0 to N - 1, where N is len(L)
[0, 1, 2]

>>> range(len(L) - 1) # goes from 0 to N - 2
[0, 1]
于 2013-04-20T06:02:43.267 回答