Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"] 
like image 958
Gianni Spear Avatar asked Oct 07 '12 11:10

Gianni Spear


People also ask

Can you slice a list of lists in Python?

With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

Is Python index slicing inclusive?

Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.


1 Answers

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.

like image 126
lvc Avatar answered Sep 17 '22 15:09

lvc