python - 在 Python 中按索引从列表中删除元素的简洁方法

标签 python optimization

我有一个字符列表和索引列表

myList = ['a','b','c','d']
toRemove = [0,2]

我想在一次操作中得到这个

myList = ['b','d']

我可以做到这一点,但有没有办法更快地做到这一点?

toRemove.reverse()
for i in toRemove:
    myList.pop(i)

最佳答案

简洁的回答

>>> myList = ['a','b','c','d']
>>> toRemove = [0,2]
>>> 
>>> [v for i, v in enumerate(myList) if i not in toRemove]
['b', 'd']
>>> 

关于python - 在 Python 中按索引从列表中删除元素的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940534/

相关文章:

qt - 如何优化 QGraphicsView 的性能?

c# - C# 编译器是否足够智能来优化此代码?

python - 值错误: Expecting value: line 1 column 1 (char 0)

optimization - Erlang:优化 mnesia 表的读/写并发性

python - Bottle gevent 和线程 : gevent is only usable from a single thread

python - Pandas :每 N 列的总和

mysql - MySQL中的索引会相互干扰吗?

algorithm - 在 C++ 中寻找优化算法来替换 Excel Solver

python - 将 2D 数组复制到 3D 中/少一行 n 次

python - 从半径为 R1 和 R2 的圆环内的图像中提取数据点