简体   繁体   中英

Python find index of last element smaller than number

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?

Nailed it, the index i want is

index = ([0]+[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. The 0 in front is added to circumvent an index error, which would occur if there are no elements smaller than 2.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM