Python:使用索引列表对列表进行切片的有效方法

Gia*_*ear 7 python indexing performance list slice

我希望知道一种有效的方法和代码保存来切割数千个元素的列表

例:

b = ["a","b","c","d","e","f","g","h"] 
index = [1,3,6,7] 
Run Code Online (Sandbox Code Playgroud)

我希望得到如下结果:

c = ["b","d","g","h"] 
Run Code Online (Sandbox Code Playgroud)

lvc*_*lvc 14

使用列表执行此操作的最直接方法是使用列表解析:

c = [b[i] for i in index]
Run Code Online (Sandbox Code Playgroud)

但是,根据您的数据究竟是什么样以及您需要使用它做什么,您可以使用numpy数组 - 在这种情况下:

c = b[index]
Run Code Online (Sandbox Code Playgroud)

会做你想要的,并且会避免大切片的潜在内存开销 - numpy数组比列表更有效地存储,切片将视图放入数组而不是制作部分副本.