简体   繁体   中英

return closest item to a given value in a list and its index

I found the following one code for searching for the nearest value to 11.1 in list a, eg: a=(1,2,3,4,5,6,7,8,9,10,11,12)

min(enumerate(a), key=lambda x: abs(x[1]-11.1))

How does the code pick the correct index? Are there any better implementations?

enumerate() function in each iteration returns a tuple where the first element is the index and the second element is the actual element of the list.

Then you are finding the minimum of it where the key is - abs(x[1] - 11.1) - which gives the absolute difference between the element and 11.1 .

Example to show enumerate behavior -

>>> l =  [10,11,12]
>>> a = enumerate(l)
>>> next(a)
(0, 10)
>>> next(a)
(1, 11)
>>> next(a)
(2, 12)

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