如何在 Python 中從另一個列表中移除索引列表?
在本文中,我們將向您展示如何使用 Python 從原始列表中刪除索引列表元素。現在我們看到完成此任務的兩種方法:
使用 pop() 方法
使用 del 關鍵字
假設我們已經獲取了一個包含一些元素的列表。我們將使用上面指定的不同方法從主列表中刪除索引列表元素。
注意
我們必須以降序對索引列表進行排序,因為從開頭刪除元素會更改其他元素的索引,並且由於索引錯位,刪除另一個元素會導致錯誤的結果。
讓我們用一個例子來演示這一點。
考慮以下列表:
list = ["Welcome," "to," "tutorialspoint," "python"]
indices List = [ 0, 2]
從開頭刪除元素的問題
如果我們從開頭刪除元素,則索引為 0 的元素“Welcome”將首先被刪除。
現在修改後的列表如下所示:
list = ["to," "tutorialspoint," "python"]
如果我們刪除索引為 2 的元素,即“python”,則修改後的列表如下所示
list = ["to," "tutorialspoint]
但結果應該是
list = ["to”,"python"]
因為索引為 0 和 2 的元素分別是“Welcome”和“tutorialspoint”。
因此,為了克服這個問題,我們從末尾刪除元素,這樣索引就不會受到影響。
方法 1:使用 pop() 函式
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表
輸入要刪除專案的索引列表
使用sorted()函式(返回給定可迭代物件的排序列表。如果 reverse=True,則以降序排序,如果 reverse=False,則以升序排序。預設為 False,即升序),透過傳遞給定的索引列表和 reverse=True 作為引數,以降序對給定的索引列表進行排序。
使用for迴圈遍歷給定的索引列表。
使用if條件語句檢查相應的迭代器索引是否小於列表長度,並使用len()函式(len() 方法返回物件中的專案數)。
如果條件為真,則使用pop()函式刪除對應索引處的專案。
刪除給定索引處的專案後列印列表。
示例
以下程式在使用 pop() 函式基於索引列表刪除主/原始列表的元素後返回列表:
# input list inputList = ["Welcome", 20, "to", "tutorialspoint", 30, "python"] # Entering the indices list at which the items are to be deleted givenIndices = [1, 4, 5] # Reversing Indices List indicesList = sorted(givenIndices, reverse=True) # Traversing in the indices list for indx in indicesList: # checking whether the corresponding iterator index is less than the list length if indx < len(inputList): # removing element by index using pop() function inputList.pop(indx) # printing the list after deleting items at the given indices print("List after deleting items at the given indices:\n", inputList)
輸出
執行上述程式將生成以下輸出:
List after deleting items at the given indices: ['Welcome', 'tutorialspoint']
我們建立了一個列表並向其中添加了一些隨機值。然後我們建立了另一個索引列表來儲存要刪除的主列表元素的索引。為了避免在刪除時發生衝突,我們以降序/遞減順序對索引列表進行了排序。之後,我們遍歷索引列表,檢查每個元素的索引是否小於主列表的長度,因為我們只能刪除索引小於列表長度的元素。然後,透過傳遞索引,我們從主列表中刪除該元素,並在從主列表中刪除索引列表索引元素後顯示最終的主列表。
方法 2:使用 del() 函式
演算法(步驟)
以下是執行所需任務的演算法/步驟:
使用sorted()函式透過傳遞給定的索引列表和 reverse=True 作為引數以降序對給定的索引列表進行排序。
使用for迴圈遍歷給定的索引列表。
使用if條件語句檢查相應的迭代器索引是否小於列表長度,並使用len()函式(len() 方法返回物件中的專案數)。
使用del關鍵字刪除給定索引(迭代器)處的列表項。
刪除索引列表的所有元素後列印列表。
語法
del list object [index]"
這是一個命令,可用於根據專案的索引位置從列表中刪除專案。
如果列表為空或指定的索引超出範圍,則 del 關鍵字將引發 IndexError。
示例
以下程式在使用 del 關鍵字基於索引列表刪除主/原始列表的元素後返回列表:
inputList = ["Welcome", 20, "to", "tutorialspoint", 30, "python"] # index list givenIndices = [0, 3] # Reversing Indices List indicesList = sorted(givenIndices, reverse=True) # Traversing in the indices list for indx in indicesList: # checking whether the corresponding iterator index is less than the list length if indx < len(inputList): # removing element by index using del keyword del inputList[indx] # printing the list after deleting items at the given indices print("List after deleting items at the given indices:\n") print(inputList)
輸出
List after deleting items at the given indices: [20, 'to', 30, 'python']
結論
在本文中,我們學習瞭如何使用 pop() 函式和 del 關鍵字從原始列表中刪除索引列表。透過一個實際示例,我們還了解了為什麼不能從開頭刪除元素。