目标很简单:有一个由 ` 分隔的 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) 没有被不断地重新评估导致数字超出范围,因为一堆数字被删除了?任何指针/提示都会很棒。非常感谢您的时间!