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

Python 交换值时获取列表索引超出范围错误,python,Python,我正在读取x,y坐标的列表(listps),并试图交换循环中的值:数组中的当前位置(I)和最小y值(k)的索引 但是,我为正在交换的(listPts[I],listPts[k]=listPts[k],listPts[I])行找到了内置的索引器:列表索引超出范围。我不知道为什么 def main(): listPts = readDataPts('Set_A.dat', 2000) def giftwrap(listPts): """Returns the convex hull

我正在读取x,y坐标的列表(
listps
),并试图交换循环中的值:数组中的当前位置(
I
)和最小y值(
k
)的索引

但是,我为正在交换的
(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
def main():
listPts=readDataPts('Set_A.dat',2000年)
def giftwrap(列表):
“”“返回使用
作为“h”元组列表的giftwrap算法
[(u0,v0),(u1,v1),…]
"""
chull=[]
n=长度(列表点)
i=0##数组中的当前位置
v=0##以前的最小角度
k=listps.index(最小值(listps,key=lambda y:(y[1],-y[0]))##具有最小y值的点的索引
minAngle=361##当前最小角度
而k!=n:
##交换listPts[i]和listPts[k]
listps[i],listps[k]=listps[k],listps[i]
##对于剩余的索引j…n
对于范围(i+1,n)内的j:
##计算点i和点j之间的角度
角度=θ(listPts[i],listPts[j])
##如果角度<当前最小角度,角度>上一个最小角度,点j!=第一点
如果(角度v和listps[j]!=listps[i]):
minAngle=角度##最小角度成为点i和点j之间的角度
k=j##最小y值成为点j的y值
v=minAngle###最小角度存储在v中,以与i的下一次迭代进行比较
i=i+1
回程槽

在循环过程中,您希望什么能阻止您的
?(看起来
k
不太可能等于
n
…它被设置为
j
,并且
j
严格小于
n
)作为调试辅助,我建议您在交换之前打印
k
I
n
的值。如果您阅读、执行和使用这些值,您可能会得到更好的帮助。