簡體   English   中英

如何在循環中更新數組索引(IndexError:列表索引超出范圍)

[英]How to update array Index in loop (IndexError: list index out of range)

我不應該使用高級功能,因為這是面試時的邏輯測試。 試圖刪除在數組中出現多次的所有數字。

測試用例:a = [1,1,2,3,2,4,5,6,7]

碼:

    def dup(a):
      i=0
      arraySize = len(a)
      print(arraySize)
        while i < arraySize:
        #print("1 = ",arraySize)
        k=i+1
          for k in range(k,arraySize):
          if a[i] == a[k]:
          a.remove(a[k])
        arraySize -= 1
        #print("2 = ",arraySize)
      i += 1
    print(a) 

結果應該是:1,2,3,4,5,6,7

但我不斷讓索引超出范圍。 我知道這是因為循環內的數組列表發生了變化,因此“while”初始索引與新索引不同。

問題是:任何方式將新索引長度(循環內的數組)與父循環(“while”循環中的索引)同步?

我唯一能想到的是在循環中使用函數。

任何提示?

每次迭代重新計算數組大小

看起來我們在這里有幾個問題。 第一個問題是您無法更新內循環( range函數)中的“停止”值。 首先,讓我們刪除它並使用另一個while循環讓我們能夠在每次迭代時重新計算數組大小。

重新檢查值已移至刪除的列表點

接下來,在您修復之后,您將遇到更大的問題。 當您使用remove它會從列表末尾移動一個值或將整個列表向左移動以使用刪除的點,並且您不會重新檢查已移入舊值刪除點的值。 要解決這個問題,我們需要在刪除元素時遞減i ,這樣可以確保我們檢查放入已刪除元素點的值。

remove vs del

在這種情況下,您應該使用del over remove remove列表上的迭代並刪除第一次出現的值,看起來我們已經知道要刪除的值的確切索引。 remove可能會工作,但它在這里的使用過多使事情復雜化。

具有最小變更集的功能代碼

def dup(a):
    i = 0
    arraySize = len(a)
    print(arraySize)
    while i < arraySize:
        k = i + 1
        while k < arraySize: # CHANGE: use a while loop to have greater control over the array size.
            if a[i] == a[k]:
                print("Duplicate found at indexes %d and %d." % (i, k))
                del a[i] # CHANGE: used del instead of remove.
                i -= 1 # CHANGE: you need to recheck the new value that got placed into the old removed spot.
                arraySize -= 1
                break
            k += 1
        i += 1
    return a

現在,我想指出,我們對上面的代碼有一些可讀性和可維護性問題。 迭代數組並以我們正在進行的方式操作迭代器有點亂,可能容易出現簡單的錯誤。 以下是我以更易讀和可維護的方式實現此問題的幾種方法。

簡單的可讀替代方案

def remove_duplicates(old_numbers):
    """ Simple/naive implementation to remove duplicate numbers from a list of numbers. """
    new_numbers = []
    for old_number in old_numbers:
        is_duplicate = False
        for new_number in new_numbers:
            if old_number == new_number:
                is_duplicate = True
        if is_duplicate == False:
            new_numbers.append(old_number)
    return new_numbers

優化的低級別替代方案

def remove_duplicates(numbers):
""" Removes all duplicates in the list of numbers in place. """
    for i in range(len(numbers) - 1, -1, -1):
        for k in range(i, -1, -1):
            if i != k and numbers[i] == numbers[k]:
                print("Duplicate found. Removing number at index: %d" % i)
                del numbers[i]
                break
    return numbers

您可以復制另一個列表中的內容並從中刪除重復項並返回列表。 例如:

duplicate = a.copy()  

f = 0  
for j in range(len(a)):  
    for i in range(len(duplicate)):  
        if i < len(duplicate):  
            if a[j] == duplicate[i]:  
                f = f+1  
                if f > 1:  
                    f = 0  
                    duplicate.remove(duplicate[i])  
    f=0  
print(duplicate) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM