交换值时获取列表索引超出范围错误

时间:2017-05-29 05:44:00

标签: python

我正在阅读x,y坐标的列表(listPts),并尝试在循环内交换值:数组中的当前位置(i),索引为最小y -value(k)。

但是,对于正在交换builtins.IndexError: list index out of range的行,我想出了(listPts[i], listPts[k] = listPts[k], listPts[i])。我不知道为什么。

def main():
    listPts = readDataPts('Set_A.dat', 2000)

def giftwrap(listPts):
    """Returns the convex hull vertices computed using the
          giftwrap algorithm as a list of 'h' tuples
          [(u0,v0), (u1,v1), ...]    
    """
    chull = []
    n = len(listPts)
    i = 0                                                            ## current position in array
    v = 0                                                            ## previous minimum angle                         
    k = listPts.index(min(listPts, key=lambda y: (y[1], -y[0])))     ## index of point with minimum y-value
    minAngle = 361                                                   ## current minimum angle
    while k != n:
        ## swap listPts[i] and listPts[k]
        listPts[i], listPts[k] = listPts[k], listPts[i]
        ## for remaining indices j...n
        for j in range(i+1, n):
            ## compute angle between point i and point j
            angle = theta(listPts[i], listPts[j])
            ## if angle < current min angle, angle > previous min angle, point j != point i
            if (angle < minAngle and angle > v and listPts[j] != listPts[i]):
                minAngle = angle     ## min angle becomes angle between point i and point j
                k = j                ## min y-value becomes point j's y value
        v = minAngle        ## min angle is stored in v to compare with next iteration of i
        i = i+1
    return chull

0 个答案:

没有答案