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

43次阅读
没有评论

共计 324 个字符,预计需要花费 1 分钟才能阅读完成。

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

  1. 使用列表推导式:
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)
  1. 使用循环:
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)

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-03-19发表,共计324字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)