Python: how to find value in list smaller than target

后端 未结 6 1225
一个人的身影
一个人的身影 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条回答
  •  旧时难觅i
    2021-01-12 09:40

    If I understand you correctly, you want the greatest value that is less than your target; e.g. in your example, if your target is 55, you want 50, but if your target is 35, you want 20. The following function should do that:

    def get_closest_less(lst, target):
        lst.sort()
        ret_val = None
        previous = lst[0]
        if (previous <= target):
            for ndx in xrange(1, len(lst) - 1):
                if lst[ndx] > target:
                    ret_val = previous
                    break
                else:
                    previous = lst[ndx]
        return str(ret_val)
    

    If you need to step through these values, you could use a generator to get the values in succession:

    def next_lesser(l, target):
        for n in l:
            if n < target:
                yield str(n)
    

    Both these worked properly from within a simple program.

提交回复
热议问题