您的代码有些错误。以下将收集每个第一个重复项的索引:def firstDuplicate(a): num = [] # list to collect indexes of first dupes for i in range(len(a)-1): # second to last is enough here for j in range(i+1, len(a)): if a[i]==a[j]: # while-loop made little sense num.append(j) # grow list and do not override it break # stop inner loop after first duplicate print(num)当然,还有更多性能算法可以实现这一点,而不是二次方的。