15

So, for example, I got a list: myList=["asdf","ghjk","qwer","tyui"]
I also have a list of index numbers of the items I want to remove: removeIndexList=[1,3] (I want to remove items 1 and 3 from the list above)

What would be the best way to do this?

4

2 回答 2

20

使用列表推导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']
于 2013-09-16T21:28:14.217 回答
7

明显的方法是行不通的:

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

问题是,在你删除#1“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]
于 2013-09-16T21:30:24.983 回答