Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove list of indices from a list in Python

Tags:

python

I have a list with points (centroids) and some of them have to be removed.

How can I do this without loops? I've tried the answer given here but this error is shown:

list indices must be integers, not list

My lists look like this:

centroids = [[320, 240], [400, 200], [450, 600]]
index = [0,2]

And I want to remove the elements in index. The final result would be:

centroids = [[400, 200]]
like image 276
Thabby07 Avatar asked Jul 07 '15 11:07

Thabby07


1 Answers

You can use enumerate within a list comprehension :

>>> centroids = [[320, 240], [400, 200], [450, 600]]
>>> index = [0,2]
>>> [element for i,element in enumerate(centroids) if i not in index]
[[400, 200]]

Note that finally you have to loop over your list to find the special indices and there is no way that do this without loop. but you can use list comprehension that performs in C language and is faster (some time 2 time faster) than python loops!

Also for getting more performance you can put your indices within a set container that has O(1) for checking membership.

like image 166
Mazdak Avatar answered Oct 22 '22 15:10

Mazdak