如何在 Python 中從列表中刪除多個項?
要從列表中刪除多個項,我們可以使用本文討論的多種方式。假設有以下輸入列表 -
["David","Jacob", "Harry", "Mark", "Anthony", "Steve", "Chris"]
當刪除多個元素“David”和“Harry”時,輸出如下 -
["Jacob", "Mark", "Anthony", "Steve", "Chris"]
從列表中刪除多個項
示例
要從列表中刪除多個項,請使用 del 關鍵字。del 允許您使用方括號新增要刪除的項。
# Creating a List mylist = ["David","Jacob", "Harry", "Mark", "Anthony", "Steve", "Chris"] # Displaying the List print("List = ",mylist) # Remove multiple items from a list using del keyword del mylist[2:5] # Display the updated list print("Updated List = ",list(mylist))
輸出
List = ['David', 'Jacob', 'Harry', 'Mark', 'Anthony', 'Steve', 'Chris'] Updated List = ['David', 'Jacob', 'Steve', 'Chris']
使用列表解析從列表中刪除多個項
示例
要從列表中刪除多個項,我們還可以使用列表解析。在此,首先我們將設定要刪除的元素,然後將其新增到列表解析中以進行刪除 -
# Creating a List mylist = ["David","Jacob", "Harry", "Mark", "Anthony", "Steve", "Chris"] # Displaying the List print("List = ",mylist) # Remove the following multiple items delItems = {"David","Anthony","Chris"} # List Comprehension to delete multiple items resList = [i for i in mylist if i not in delItems] # Display the updated list print("Updated List = ",resList)
輸出
List = ['David', 'Jacob', 'Harry', 'Mark', 'Anthony', 'Steve', 'Chris'] Updated List = ['Jacob', 'Harry', 'Mark', 'Steve']
使用 remove() 從列表中刪除多個項
示例
在此示例中,我們將從列表中刪除多個項。要刪除的項的倍數是 5 -
# Creating a List mylist = [2, 7, 10, 14, 20, 25, 33, 38, 43] # Displaying the List print("List = ",mylist) # Delete multiple items (divisible by 5) for i in list(mylist): if i % 5 == 0: mylist.remove(i) # Display the updated list print("Updated List = ",mylist)
輸出
List = [2, 7, 10, 14, 20, 25, 33, 38, 43] Updated List = [2, 7, 14, 33, 38, 43]
使用索引從列表中刪除多個項
示例
在這裡,我們將提供要刪除的項的索引 -
# Creating a List mylist = ["David","Jacob", "Harry", "Mark", "Anthony", "Steve", "Chris"] # Displaying the List print("List = ",mylist) # Remove the items at the following indexes delItemsIndex = [1, 4] # List Comprehension to delete multiple items for i in sorted(delItemsIndex, reverse = True): del mylist[i] # Display the updated list print("Updated List = ",mylist)
輸出
List = ['David', 'Jacob', 'Harry', 'Mark', 'Anthony', 'Steve', 'Chris'] Updated List = ['David', 'Harry', 'Mark', 'Steve', 'Chris']
廣告