Python: an efficient way to slice a list with a index list

梦想与她 提交于 2019-11-30 14:21:01

The most direct way to do this with lists is to use a list comprehension:

c = [b[i] for i in index]

But, depending on exactly what your data looks like and what else you need to do with it, you could use numpy arrays - in which case:

c = b[index]

would do what you want, and would avoid the potential memory overhead for large slices - numpy arrays are stored more efficiently than lists, and slicing takes a view into the array rather than making a partial copy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!