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

2024-04-20 07:14:15 发布

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

我正在阅读x,y坐标的列表(listPts),并试图交换循环中的值:数组(i)中的当前位置和最小y值的索引(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

Tags: andofinindexvaluedefrangecurrent