所以,例如,我得到了一个清单:myList=["asdf","ghjk","qwer","tyui"]
我还有一个我要删除的项目的索引号列表:removeIndexList=[1,3]
(我想从上面的列表中删除项目1和3)
最好的方法是什么?
答案 0 :(得分:19)
将列表理解与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']
答案 1 :(得分: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]