Python: how to find value in list smaller than target

后端 未结 6 1233
一个人的身影
一个人的身影 2021-01-12 08:51

For example I have a non-ordered list of values [10, 20, 50, 200, 100, 300, 250, 150]

I have this code which returns the next greater value:

def GetN         


        
6条回答
  •  孤独总比滥情好
    2021-01-12 09:39

    A better and much faster (code and cpu wise) way is to use bisect module which does binary search but for that you will need to sort the list first, here is the sample usage:

    import bisect
    
    mylist = [10, 20, 50, 200, 100, 300, 250, 150]
    mylist.sort()
    
    index = bisect.bisect(mylist, 55)
    print "Greater than target", mylist[index]
    print "Smaller than or equal to target", mylist[index-1]
    

    output:

    Greater than target 100
    Smaller than or equal to target 50
    

    Also you will need to check the returned index, if it is 0 it means you have passed target lower than the lowest

提交回复
热议问题