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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With