简体   繁体   中英

given a sorted list, find the index of number

Given a sorted list and a number n , find the index in the list that precedes n in the most efficient (fastest) way.

sorted list example:

x_list = [1, 3.5, 5, 9.2, 20, 50.75]

number n , say n = 7.5

Example answer: the index of the value in the list that precedes n is 2 .

This is what i have tried so far:

x_list = [1, 3.5, 5, 9.2, 20, 50.75]

n = 7.5
for i, v in enumerate(x_list):
    if v < n: xlow = i
    else: break
print(xlow)

Can i do a quicker find than the above method?

Note: This list is sorted whereas other questions of the same nature are unsorted .

You can use bisect to perform a binary search:

import bisect

n = 7.5

index = bisect.bisect_left(x_list, n)-1

output: 2

NB. In case the target is before the first index, this will return -1 , which you can avoid using max(0, bisect.bisect_left(x_list, n)-1) if needed.

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