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

后端 未结 1 2023
甜味超标
甜味超标 2021-01-02 13:52

I wish to know an efficient way and code saving to slice a list of thousand of elements

example:

b = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\         


        
1条回答
  •  独厮守ぢ
    2021-01-02 14:38

    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.

    0 讨论(0)
提交回复
热议问题