从 Python 中的列表中删除多个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18837607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove multiple items from list in Python
提问by mid_kid
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)
因此,例如,我有一个列表:myList=["asdf","ghjk","qwer","tyui"]
我还有一个要删除的项目的索引号列表:(removeIndexList=[1,3]
我想从上面的列表中删除项目 1 和 3)
What would be the best way to do this?
什么是最好的方法来做到这一点?
采纳答案by Martijn Pieters
Use a list comprehension with enumerate()
:
使用列表理解enumerate()
:
newlist = [v for i, v in enumerate(oldlist) if i not in removelist]
making removelist
a set
instead will help speed things along:
制作removelist
一个set
代替将有助于加快速度:
removeset = set(removelist)
newlist = [v for i, v in enumerate(oldlist) if i not in removeset]
Demo:
演示:
>>> oldlist = ["asdf", "ghjk", "qwer", "tyui"]
>>> removeset = set([1, 3])
>>> [v for i, v in enumerate(oldlist) if i not in removeset]
['asdf', 'qwer']
回答by abarnert
The obvious way will not work:
显而易见的方法是行不通的:
list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3]
for index in removelist:
del list[index]
The problem is that after you've deleted #1, "ghjk", everything after that gets shifted forward. So #3 is no longer "tyui", it's past the end of the list.
问题是,在您删除 #1"ghjk" 之后,之后的所有内容都会向前移动。所以#3 不再是“tyui”,它已经超出了列表的末尾。
You can solve this by making sure you walk backward:
您可以通过确保向后走来解决此问题:
list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3]
for index in sorted(removelist, reverse=True):
del list[index]
However, it's generally better to just build a new filtered list instead, as suggested by Martijn Pieters:
但是,正如 Martijn Pieters 所建议的那样,通常最好只构建一个新的过滤列表:
list = [v for i, v in enumerate(list) if i not in removelist]