Python:复制列表并同时删除元素

2024-10-01 00:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试创建一个没有特定元素的列表副本。我现在就是这样做的:

oldList[1,23,4,3,5,345,4]
newList = oldList[:]
del newList[3]
doSomthingToList(newList)

我想知道是否有更好的更雄辩的方法来做到这一点,而不是复制列表,然后删除两行中的元素?你知道吗


Tags: 方法元素列表副本del新手newlistoldlist
3条回答

用“切片”试试这个:

>>> oldList = [1, 2, 3, 4, 5]
>>> newList = oldList[:2] + [oldList[3:]
>>> newList
[1, 2, 4, 5]
oldList[1,23,4,3,5,345,4]
newList = oldlist[:3] + oldList[4:]
doSomthingToList(newList)

使用list comprehension

>>> oldList = [1,23,4,3,5,345,4]
>>> newList = [x for i, x in enumerate(oldList) if i != 3] # by index
>>> newList
[1, 23, 4, 5, 345, 4]

>>> newList = [x for x in oldList if x != 4] # by value
>>> newList
[1, 23, 3, 5, 345]

相关问题 更多 >