简体   繁体   中英

Find the previous number in a list of float and integer

i have a list of float and integers like below

[2,4.635,9,18,27.548,36]

For a given input i want to find the previous number of that input in the list by comparing that number with the numbers in list For example: if i give 8.9 as input i should get 4.635 as the output, is there any builtin function for this

You can use bisect to find the insertion point of a value in a sorted list:

import bisect 
li=[2,4.635,9,18,27.548,36]

>>> li[bisect.bisect_left(li,8.9)-1]    
4.635     

You could also just use a simple for loop and zip on a sorted list as well:

for lo,hi in zip(li,li[1:]):
    if lo< 8.9 <=hi:
        print lo 
        break   

I cannot remember any builtin method for this, but it is quite easy to implement:

def get_previous(l, query):
    return max([x for x in l if x<query])

query = 8.9
l = [2,4.635,9,18,27.548,36]
result = get_previous(l, query)

If the list is sorted, there could be better ways to achieve this (binary search), but you don't state that fact.

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