如何在 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']
广告