使用del时列表出现索引错误,无法计算它

2024-10-01 17:22:18 发布

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

我是新的编程,所以这个代码可能是相当垃圾。无论如何,我要做的是取两个列表(xy1,xy2),它们包含一个矩形的角点,看它们是否与其他矩形重叠。我使用的格式是x1,y1在数组xy1中,x2,y2在数组xy2中。到目前为止,我只使用x轴,所以两个数组中的每个其他条目。我的问题是,当我找到那些重叠的并删除它们时,我会得到一个索引错误。我相信这个问题与使用del和我的for max循环有关,我使用数组的len得到这个循环。如果没有重叠并触发删除的调用,代码有时也可以工作。如有任何建议,我们将不胜感激。谢谢

#1,3 are x cords for first rect, 5 and 8 are x cords for second rect
xy1=[1,6,5,12,1,17]
xy2=[3,9,8,16,4,19]
def make(xy1,xy2):
    count0=0
    for count1 in range(count0,len(xy1),2):
        for count2 in range(count0,len(xy2),2):
            if xy1[count1] in range(xy1[count2],xy2[count2]) and not (count1==count2):
                xy1=removed(xy1,count1)
                xy2=removed(xy2,count1)
    return xy1,xy2

def removed(xy1,count1):
    #removes the x,y that was overlapped along with the other 2 corners of the rect
    del xy1[count1:count1+2]
    return xy1

make(xy1,xy2)

print xy1,xy2

Tags: the代码inrectforlenrange数组
2条回答

问题是,每次删除某个内容时,数组xy1的长度都在缩小。但是你的迭代器计数一直在增加而没有考虑到这一点。如果每次在del之前打印xy1count1,您可以更清楚地看到行为

就像TJD说的,你有一个数组正在缩小,所以你会得到一个索引超出范围的错误。你知道吗

在不改变代码的情况下,您可以通过向后查看列表来解决这个问题。如果您更改了过程的前三行,您应该会得到所需的结果,并且不再出现错误。你知道吗

def make(xy1,xy2):
count0=-1
for count1 in range(len(xy1)-2,count0,-2):
    for count2 in range(len(xy2)-2,count0,-2):
        if xy1[count1] in range(xy1[count2],xy2[count2]) and not (count1==count2):
            xy1=removed(xy1,count1)
            xy2=removed(xy2,count1)
return xy1,xy2

相关问题 更多 >

    热门问题