Extract the value closest to a value from a Python list element

Note that it took some time to retrieve the value closest to a certain value from the list in Python.

Failure example

I saw how to use numpy's searchsorted function on the net, but this function inserts a value into the list Since it is a function that returns the index when doing so, it does not always return the index of the value closest to a certain value.

** Example of actual failure **

Failure example.py


# coding: utf-8

import numpy as np


def getNearestValue(list, num):
    
    #Get index when inserting in ascending order
    sortIdx = np.searchsorted(list, num, side='left')
    return list[sortIdx]
    

if __name__ == "__main__":

    list = [0, 0.5, 1]

    print(getNearestValue(list, 0.1))  # →0 OK
    print(getNearestValue(list, 0.4))  # →0 NG

The closest value to 0.4 in the list element of the above code is 0.5, but 0 is returned.

solution

~~ Therefore, we implemented a function that calculates the difference between the target values from the peripheral elements of the index obtained by the searchsorted function and extracts the value closest to a certain value. ~~

** Addendum: 2016/08/24 ** kochory gave me a code that has been greatly streamlined. It is implemented by calculating the difference between a certain value and the elements in the list and finding the index of the minimum value. Thank you!

getNearestValue_sample2.py


# coding: utf-8

import numpy as np


def getNearestValue(list, num):
    """
Overview:A function that returns the value closest to a value from the list
    @param list:Data array
    @param num:Target value
    @return The value closest to the target value
    """

    #Calculate the difference between the list element and the target value and get the index of the minimum value
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]
    

if __name__ == "__main__":

    list = [0, 0.5, 1]
    
    print(getNearestValue(list, -0.1)) # →0
    print(getNearestValue(list, 0.1))  # →0
    print(getNearestValue(list, 0.4))  # →0.5
    print(getNearestValue(list, 0.5))  # →0.5
    print(getNearestValue(list, 0.6))  # →0.5
    print(getNearestValue(list, 0.8))  # →1
    print(getNearestValue(list, 1.2))  # →1

Recommended Posts

Extract the value closest to a value from a Python list element
How to get the last (last) value in a list in Python
A python amateur tries to summarize the list ②
[Python] How to remove duplicate values from the list
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
python / Make a dict from a list.
Extract the value of dict or list as a string
How to find the first element that matches your criteria in a Python list
How to determine the existence of a selenium element in Python
Try to extract a character string from an image with Python3
Pass a list by reference from Python to C ++ with pybind11
How to remove duplicates from a Python list while preserving order.
Find all patterns to extract a specific number from the set
[Python] A program that rotates the contents of the list to the left
[Python] How to convert a 2D list to a 1D list
Send a message from Python to Slack
# 5 [python3] Extract characters from a character string
Python amateurs try to summarize the list ①
[Python] What is a formal argument? How to set the initial value
Extract lines that match the conditions from a text file with python
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to get a value from a parameter store in lambda (using python)
[Python] How to use the enumerate function (extract the index number and element)
[Python] List Comprehension Various ways to create a list
Edit Excel from Python to create a PivotTable
How to open a web browser from python
How to clear tuples in a list (Python)
Make a copy of the list in Python
How to generate a Python object from JSON
How to extract coefficients from a fractional formula
Python Note: When assigning a value to a string
[Algorithm x Python] How to use the list
[Python] Throw a message to the slack channel
How to pass the execution result of a shell command in a list in Python
[python] How to sort by the Nth Mth element of a multidimensional array
Use PIL in Python to extract only the data you want from Exif
[Python] Solution to the problem that elements are linked when copying a list
Python script to get a list of input examples for the AtCoder contest
[Python] I tried to get the type name as a string from the type function
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary
How to get a list of files in the same directory with python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
How to retrieve the nth largest value in Python
The wall of changing the Django service from Python 2.7 to Python 3
How to write a list / dictionary type of Python3
Python points from the perspective of a C programmer
I wanted to use the Python library from MATLAB
Things to note when initializing a list in Python
From buying a computer to running a program with python
The first step to getting Blender available from Python
[Python] I want to make a nested list a tuple
Consider a conversion from a Python recursive function to a non-recursive function
How to post a ticket from the Shogun API
Python script to create a JSON file from a CSV file
[Python] How to output the list values in order
[Python] How to call a c function from python (ctypes)
How to create a kubernetes pod from python code
A little bit from Python using the Jenkins API