删除列表中的项目并获取新列表? [英] Remove an item in list and get a new list?

查看:82
本文介绍了删除列表中的项目并获取新列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有几个关于从列表中删除项目的主题,包括使用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]

这篇关于删除列表中的项目并获取新列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆