-1

目标很简单:有一个由 ` 分隔的 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(array),我似乎还是设法在此过程中超出范围。我的猜测是 len(number) 没有被不断地重新评估导致数字超出范围,因为一堆数字被删除了?任何指针/提示都会很棒。非常感谢您的时间!

4

1 回答 1

0

好吧,看来我的担心是正确的。在第二个循环中,j 设法越过 len(number) 导致错误...

#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()

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

于 2017-09-03T14:06:58.977 回答