我看到有几个关于从列表中删除项目的主题,包括使用remove()
,pop()
和del
。但是这些都不是我要找的,因为我想在删除项目时获取一个新列表。例如,我想做这个:
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]
我该怎么做?
我看到有几个关于从列表中删除项目的主题,包括使用remove()
,pop()
和del
。但是这些都不是我要找的,因为我想在删除项目时获取一个新列表。例如,我想做这个:
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]
我该怎么做?
如果您想要一个没有第三个元素的新列表,则:
b = a[:2] + a[3:]
如果您想要一个不包含值“3”的列表:
b = [n for n in a if n != 3]
b = a[:2] + a[3:]
。谢谢@Yevhen。我以为Python有一些内置函数可以做到这一点,也许并没有。但这是一个很好的解决方案! - user3768495
a.pop(2)
到底有什么问题? - barak manoslist
对象。 - vishes_shellb = a[:2]+a[3:]
- Chris_Rands