Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套循环中的输出长度不匹配?_Python_Arrays_Indexing_Nested Loops - Fatal编程技术网

Python 嵌套循环中的输出长度不匹配?

Python 嵌套循环中的输出长度不匹配?,python,arrays,indexing,nested-loops,Python,Arrays,Indexing,Nested Loops,我对循环的输出数量有问题 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(s

我对循环的输出数量有问题

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个点

迭代后,邻域数组仅保存207个值(即len(neights)=207),但所有208个值都应有第七个最近邻。 有人能告诉我问题出在哪里吗?

这行:

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

可能是问题,
范围
不包含停止参数,因此
-1
缺少最后一个元素

例如

但是


很抱歉,缩进现在格式正确。选择变量的值是多少?选择变量有208个位置值。这可能与您遇到的问题没有直接关系,但迭代列表中所有唯一值对的更为简洁的方法是使用
itertools.compositions
。itertools.compositions(selection,2)中a,b的代码
:可以取代当前的大部分循环逻辑。@Blckknght我认为OPs代码可能更像pythonic,特别是不迭代仅用作索引的索引,但我认为
itertools.compositions
不会起作用,因为外循环对内循环的结果进行额外的处理。相反,我会使用距离计算函数,然后将
heapq.nsmallest
与生成器表达式一起使用。我认为它修复了它,当-1被删除时,它会给出208个值。
for k in range(0, len(selection)-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]