在通过数组检查python 2.7

时间:2017-09-03 13:20:01

标签: python-2.7 list indexoutofrangeexception xrange

目标很简单:有一个x号由`分隔的文件。如果文件中有数字的共同体,则应删除它们。我决定通过比较n成员和从n到len(array)的所有其他成员来解决这个问题。代码:

    #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(数字)没有被不断重新评估,导致数字超出范围,因为一堆数字被删除了? 任何指针/提示都会很棒。非常感谢你的时间!

1 个答案:

答案 0 :(得分:0)

好吧,似乎我的恐惧是正确的。在第二个循环中,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()

没有try语句就可以正常工作。我不确定为什么会这样,但似乎确实如此。如果你们有一个很好的解释:/