从Python中删除列表中的多个项目

mid*_*kid 15 python list

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

最好的方法是什么?

Mar*_*ers 19

使用列表理解enumerate():

newlist = [v for i, v in enumerate(oldlist) if i not in removelist]
Run Code Online (Sandbox Code Playgroud)

removelist一个set代替将有助于加快速度:

removeset = set(removelist)
newlist = [v for i, v in enumerate(oldlist) if i not in removeset]
Run Code Online (Sandbox Code Playgroud)

演示:

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


aba*_*ert 7

显而易见的方法是行不通的:

list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3] 
for index in removelist:
    del list[index]
Run Code Online (Sandbox Code Playgroud)

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


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

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

但是,正如Martijn Pieters所建议的那样,通常建立一个新的过滤列表通常会更好:

list = [v for i, v in enumerate(list) if i not in removelist]
Run Code Online (Sandbox Code Playgroud)