[英]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) 我发现以下代码用于搜索列表a中最接近11.1的值,例如: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. 每次迭代中的
enumerate()
函数返回一个元组,其中第一个元素是索引,第二个元素是列表的实际元素。
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
. 然后,在键为
abs(x[1] - 11.1)
位置找到最小值,它给出了元素和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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.