How to get the list index where you can find the closest number?
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) =>
Math.Abs(x-number) < Math.Abs(y-number) ? x : y);
We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.
Use numpy. argmin(), to obtain the index of the smallest element in difference_array[]. In the case of multiple minimum values, the first occurrence will be returned. Print the nearest element, and its index from the given array.
By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string.
To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.
If you want the index of the closest number this will do the trick:
int index = list.IndexOf(closest);
You can include the index of each item in an anonymous class and pass it through to the aggregate function, and be available at the end of the query:
var closest = list
.Select( (x, index) => new {Item = x, Index = index}) // Save the item index and item in an anonymous class
.Aggregate((x,y) => Math.Abs(x.Item-number) < Math.Abs(y.Item-number) ? x : y);
var index = closest.Index;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With