Python deletes multiple elements in the list [four methods]

1 Using slices to remove multiple elements

Use the index to delete the corresponding index element
change the original list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
del my_list[2:5]  # 删除索引2到4之间的元素
print(my_list)
# [1, 2, 6, 7, 8, 9]

2 Using list comprehensions

The element to be deleted or the index of the element to be deleted is required
Create a new list without changing the original list

# 1 直接利用删除要素
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
elements_to_remove = [3, 5, 7]
# 循环
my_list = [x for x in my_list if x not in elements_to_remove]
print(my_list)
# [1, 2, 4, 6, 8, 9]
# *****************************************
# 2 利用删除要素的索引
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
elements_to_remove_index = [2, 4, 6]
# 循环
my_list = [x for x in my_list if x not in elements_to_remove_index]
print(my_list)
# [1, 3, 5, 7, 8, 9]
# 3 使用enumerate(),返回列表的【indexs,datas】
lis = ['A','B','C','D','E','F','G']
index_list = [1,2,6]
lis = [temp_data for index, temp_data in enumerate(lis) if index not in index_list]
print('删除后lis的值:%s' %lis)
# 删除后lis的值:['A', 'D', 'E', 'F']

The above two methods give the same result

3 Use the romove() function

elements to be removed
change the original list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
elements_to_remove = [3, 5, 7]
# 循环去除
for element in elements_to_remove:
    my_list.remove(element)
print(my_list)
# [1, 2, 4, 6, 8, 9]

4 Use the pop() function

index of the element to be removed
change the original list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
indices_to_remove_index = [2, 4, 6]
# 将索引按照倒序排列
indices_to_remove_index.sort(reverse=True)  # 从后往前删除,避免索引错位
# [6, 4, 2]
for index in indices_to_remove_index:
    my_list.pop(index)
print(my_list)
# [1, 2, 4, 6, 8, 9]

Guess you like

Origin blog.csdn.net/weixin_45913084/article/details/132224546