Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing consecutive occurrences from end of list python

I have a numpy array:

ar = np.array([True, False, True, True, True])

If the last element is True, I want to remove all of the consecutive true elements at the end of the array. So for example

magic_func(ar) => [True, False]

If ar = [True, False, True, False, True]. Then

magic_func(ar) => [True, False, True, False]

If ar = [True, False, False], the function does nothing, because the last element is False

Is there a one liner in python to do this? using a numpy library or something

like image 865
Michael Avatar asked May 01 '14 00:05

Michael


People also ask

How do I remove consecutive elements from a list in Python?

Using the groupby function, we can group the together occurring elements as one and can remove all the duplicates in succession and just let one element be in the list. This function can be used to keep the element and delete the successive elements with the use of slicing.

How do you remove the last 3 of a list in Python?

The pop() method will remove the last element from the list, So to remove the last k elements from the Python List, we need to perform the pop() operation k times.

How do I remove one occurrence from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.


1 Answers

This one line function should work, but looks very nasty and probably not efficient lol. Basically the idea is to find the most right False and return all values before False

def magic_func(a):
    return a[:len(a)-np.where(a[::-1]==False)[0][0]] if np.where(a[::-1]==False)[0].size>0 else a[:0]

>>> a = np.array([False, True, True, True, True])
>>> magic_func(a)
array([False], dtype=bool)
like image 181
xbb Avatar answered Sep 28 '22 22:09

xbb