Home > OS >  Python find index of last element smaller than number
Python find index of last element smaller than number

Time:04-20

I have a list of numbers from 0 to 3 and I want to remove every number that is smaller than 2 xor is not connected to the last 3 in the list. It is also going to be done about 200 Million times so it should preferably perform well. For example, I could have a list like that:

listIwantToCheck = [3, 0, 1, 2, 0, 2, 3, 2, 2, 3, 2, 0, 2, 1]
listIWantToGet = [2, 3, 2, 2, 3]

I already have the index of the last 3 so what I would do is:

listIWantToGet = listIWantToCheck[??? : indexOfLastThree   1]

??? being 4 in this instance. It is the index with the mentioned conditions. So How do I get the index of the last number smaller than 2?

CodePudding user response:

So if i get this right you want to get the index of the last number smaller than 2 that comes before the last 3.

My approach would be to take the part of the list from index 0 to the index of the last 3 and then reverse the list and check if the number is smaller than 2.

If you however want to get the last 2 of the entire list just reverse it and loop through it the same way

for i in listIWanttoCheck[0:indexOfLastThree].reverse():
    if i <2:
        return listIWanttoCheck.index(i)

Correct me if I missunderstood your problem

CodePudding user response:

Nailed it, the index i want is

index = [i for i, e in enumerate(listIWantToCheck[:indexOfLastThree]) if e < 2][-1]   1

List comprehension is truly beautiful. I enumerated through the slice and created a list of all indices, which point to a number smaller than 2 and took the last.

  • Related