删除列表中的项目并获取新列表?

编程入门 行业动态 更新时间:2024-10-24 10:17:41
本文介绍了删除列表中的项目并获取新列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我看到有几个关于从列表中删除项目的主题,包括使用remove(),pop()和del.但是这些都不是我想要的,因为我想在删除项目时获得一个新列表.例如,我要这样做:

I saw there are several topics on removing items from a list, including using remove(), pop(), and del. But none of these is what I am looking for, since I want to get a new list when the items are removed. For example, I want to do this:

a = [1, 2, 3, 4, 5, 6] <fill in > # This step somehow removes the third item and get a new list b and let b = [1, 2, 4, 5, 6]

我该怎么做?

推荐答案

如果要创建一个没有第三个元素的新列表,则:

If you want to have a new list without the third element then:

b = a[:2] + a[3:]

如果您想要一个没有值'3'的列表:

If you want a list without value '3':

b = [n for n in a if n != 3]

更多推荐

删除列表中的项目并获取新列表?

本文发布于:2023-11-22 20:49:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!