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']