简体   繁体   中英

How to check if a value is in between values in a list? (Python)

I want to check if a value exists in between two numbers in a sorted list and print what two numbers it exists between. For example, if the list is [1, 4, 8, 12, 16, 20] and I want to see what two numbers the number 3 is between, 1 and 4 should be printed out. Is there any way to do this in python preferably without importing a module?

If the list is sorted, you could use bisect.bisect :

import bisect

lst = [1, 4, 8, 12, 16, 20]

i = bisect.bisect(lst, 3)
print(lst[i - 1], lst[i])

Output

1 4

UPDATE

Without importing a module use:

lst = [1, 4, 8, 12, 16, 20]
i = next(j for j, e in enumerate(lst) if e >= 3)
print(lst[i - 1], lst[i])

Output

1 4

Note that the time complexity of the second approach is O(n) vs O(logn) of bisect . As an alternative you could implement bisect, in the end is justbinary search .

I am not sure if there is a inbuilt function for this but you can check it very easily by iterating over the list and take a variable as input which you want to compare. If list is not sorted in that case may be you can sort the list first.

I was going to suggest using range()

You can have list like so:

list = [1, 4, 5, 15, 22]
is_in_range = 3 in range(list[0], list[1]) # or any other element of the list - you can even iterate over this
print(is_in_range)

Not the best solution but works.

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