我希望知道一种高效的方法和代码来切分一个包含数千个元素的列表的方式,并且希望能够节省代码量。
示例:
示例:
b = ["a","b","c","d","e","f","g","h"]
index = [1,3,6,7]
我希望得到如下的结果:
c = ["b","d","g","h"]
b = ["a","b","c","d","e","f","g","h"]
index = [1,3,6,7]
我希望得到如下的结果:
c = ["b","d","g","h"]
使用列表推导式是最直接的处理列表的方法:
c = [b[i] for i in index]
但是,根据您的数据实际情况和其他需要完成的任务,您可以使用numpy数组 - 在这种情况下:
c = b[index]
使用numpy数组来进行切片操作可以达到你想要的效果,并且避免了大型切片操作可能带来的内存开销 - numpy数组比列表存储更有效率,而且切片只是对数组的视图操作,而不是部分复制。