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']
显而易见的方法行不通:
问题是,删除了“ghjk”之后,之后的所有内容都会向前移动。所以#3不再是“tyui”,它已经超过了列表的末尾。
你可以通过确保向后走来解决这个问题:
不过,通常最好是建立一个新的筛选列表,而不是像Martijn Pieters建议的那样:
对
enumerate()
使用列表理解:相反,让
removelist
变成set
将有助于加快速度:演示:
相关问题 更多 >
编程相关推荐