So I have a list
stock = [5,6,8,4,8,3,6,4]
val = 5
I want to get the index of the element closest to the 1st occurrence of the val variable in the list. So what I want to get will be 4 with index 3. if val = 8 then I will get 6 with index 1, if val = 3, since its the lowest value, I will get -1 I have tried using this code.
closest = min(range(len(stock)), key=lambda i: abs(stock[i]-val))
but it just returns back the index of val variable
This involves a lot of iterations, but still one way to find what you need... Should be modified if negative values are also in the picture.
def one_expensive_way_to_find_what_you_need(list_, val):
try:
return list_.index(max((_ for _ in stock if _ < val)))
except:
return -1
As Feodoran already pointed out , your solution does not handle closest but less than val
part that you want, and also the -1
edge-case. Hence it gives you index of the val
variable, since that always has difference of 0
which will be returned by the min
.
You need something like -
INF = 10 ** 9
closest = min(
range(len(stock)),
key=lambda i: abs(stock[i] - val) if stock[i] < val else INF
)
if closest == 0 and stock[0] >= val:
closest = -1
The if
condition in the lambda
takes care of the less than val
part by assigning the difference to an arbitrarily high number, which in my case, I've taken as 10**9
. Depending on your use case, this could be kept higher. Also, the edge-case of val
being min(stock)
is handled by the last 2 lines, needed due to the solution approach you've taken.
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.