python怎么删除列表中多个元素

可以使用列表推导式或循环来删除列表中的多个元素。以下是两种方法:

使用列表推导式:

my_list = [1, 2, 3, 4, 5]
elements_to_remove = [2, 4]

new_list = [x for x in my_list if x not in elements_to_remove]

print(new_list)

使用循环:

my_list = [1, 2, 3, 4, 5]
elements_to_remove = [2, 4]

new_list = []
for x in my_list:
    if x not in elements_to_remove:
        new_list.append(x)

print(new_list)

无论使用哪种方法,都可以实现删除列表中的多个元素。

阅读剩余
THE END