How to find out between which two lists in a list of lists a given number is?

时间:2018-03-08 22:12:28

标签: python-3.x list

I have a list of list containing some numbers like this:

l_l = [[4], [6], [17], [23], [42]]

I need to find out, between which two numbers the number 20 is and print the smallest number of these two. To be more specific: In this situation the number 20 is between 17 and 23, so number 17 should be printed. I have to assume I do not know that the number is 20, so it should work without knowing the number and without knowing how many lists there are in the list of lists. I have tried with a while loop, but I get an infinite loop. I have no other idea about how to solve this problem. Can somebody help be out?

1 个答案:

答案 0 :(得分:0)

试试这个:

for i in range(len(l_l)): ## Loop through the range of possible indices
    if your_num <= l_l[i][0]: ## Check when the elements have started to exceed/equal your number
        print(l_l[i-1][0]) ## The number before must be the smaller one
        break ## Stop running the loop (without this, _all_ numbers greater than yours will be printed, which isn't what we want)