在Python中从列表中删除多个项

2024-09-27 04:27:48 发布

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

例如,我得到了一个列表:myList=["asdf","ghjk","qwer","tyui"]
我还有一个要删除项的索引号列表:removeIndexList=[1,3](我要从上面的列表中删除项1和3)

最好的办法是什么?


Tags: 列表办法asdfmylistremoveindexlisttyuighjkqwer
2条回答

显而易见的方法行不通:

list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3] 
for index in removelist:
    del list[index]

问题是,删除了“ghjk”之后,之后的所有内容都会向前移动。所以#3不再是“tyui”,它已经超过了列表的末尾。


你可以通过确保向后走来解决这个问题:

list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3] 
for index in sorted(removelist, reverse=True):
    del list[index]

不过,通常最好是建立一个新的筛选列表,而不是像Martijn Pieters建议的那样:

list = [v for i, v in enumerate(list) if i not in removelist]

enumerate()使用列表理解:

newlist = [v for i, v in enumerate(oldlist) if i not in removelist]

相反,让removelist变成set将有助于加快速度:

removeset = set(removelist)
newlist = [v for i, v in enumerate(oldlist) if i not in removeset]

演示:

>>> oldlist = ["asdf", "ghjk", "qwer", "tyui"]
>>> removeset = set([1, 3])
>>> [v for i, v in enumerate(oldlist) if i not in removeset]
['asdf', 'qwer']

相关问题 更多 >

    热门问题