在 Python 中刪除範圍內的元素
直接使用元素的索引和 del 函式從 python 中刪除單個元素非常簡單。但有時我們可能需要在組索引中刪除元素。本文探討了僅從列表中刪除指定在索引列表中的那些元素的方法。
使用 sort 和 del
在此方法中,我們建立一個包含要刪除的索引值的列表。我們對其進行排序並逆序,以保留列表元素的原始順序。最後,我們對那些特定索引位置的原始給定列表應用 del 函式。
示例
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]
# Print result
print("List after deleted elements : " ,Alist)輸出
執行上面的程式碼,會得到以下結果 −
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]
排序並逆序後的 idx_list 變成了 [0,1,3]。因此,僅從這些位置刪除元素。
使用 enumerate 和 not in
我們還可以在 for 迴圈中,透過使用 enumerate 和 not in 子句來編寫上面的程式。結果與上述相同。
示例
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]
# Print result
print("List after deleted elements : " ,Alist)輸出
執行上面的程式碼,會得到以下結果 −
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP