简体   繁体   中英

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

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"] 
index = [1,3,6,7] 

I wish a result like as:

c = ["b","d","g","h"] 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM