在Python 2.7中查看阵列检查重复项时,列出了范围



目标很简单:有一个由x隔开的文件。如果文件中的数字有疑虑,则应删除它们。我决定通过将n个成员与从N到Len(数组)的所有其他成员进行比较来解决此问题。代码:

    #deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
    if each=='`':
        number.append(''.join(numb))
        numb=[]
    else:
        numb.append(each)
i,j=0,0
for i in xrange(len(number)): #we don't need to compare last number
    for j in xrange(i+1,len(number)-1):#don't need to compare to itself
        #print(len(number)," ",i," ",j)
        if number[i]==number[j]:
             number.pop(j) #tried del number[j]

questioned.close()

但是,即使我指定Xrange应该转到Len(数组),我似乎设法超出了范围。我的猜测是,LEN(数字)并未不断重新评估,导致数字超出范围,因为一堆数字被删除了?任何指针/技巧都会很棒。非常感谢您的时间!

好吧,我的恐惧似乎是正确的。在第二个循环中,J设法越过Len(数字),这导致错误...

#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
    if each=='`':
        number.append(''.join(numb))
        numb=[]
    else:
        numb.append(each)
i,j=0,0
def compare(number,i,j):
    if number[i]==number[j]:
        number.pop(j)
        compare(number,i,j)
    return number
for i in xrange(len(number)):
    for j in xrange(i+1,len(number)-1):
        if j>len(number)-1: 
            break
        #print(len(number)," ",i," ",j)
        #try:
            compare(number,i,j)
        #except: print('i,j',i,' ',j,'len ',len(number))
questioned.close()

无需尝试语句就可以正常工作。我不确定为什么会发生这种情况,但确实如此。如果你们有一个很好的解释:/

相关内容

  • 没有找到相关文章

最新更新