Search code examples
pythonlistnestednested-lists

get the nearest nested list from a given nested list


So I have a 2 values [-82.819309,40.081296] and a list of multiple nested values like

[[-83.0347849999999, 39.945993],
 [-82.957851, 40.060118],
 [-82.994303, 40.013227],
 [-82.8265609999999, 39.9207779999999],
 [-82.9984709999999, 39.887616],
 ...]

Now I want to get the list from the nested list whose difference from the two values is the minimum. something like

>>> getmin([1,2], [[1,1],[1,4],[2,3],[3,2]]) 
[1,1]

Logic:

[1,2] - [1,1] = abs(1-1) + abs(2-1) -> 1
[1,2] - [1,4] = abs(1-1) + abs(2-4) -> 2
[1,2] - [2,3] = abs(1-2) + abs(2-3) -> 2
[1,2] - [3,2] = abs(1-3) + abs(2-2) -> 2

Is there a way to do this?


Solution

  • You can use very simple code:

    import numpy as np
    
    mylist = [[-83.0347849999999, 39.945993],
     [-82.957851, 40.060118],
     [-82.994303, 40.013227],
     [-82.8265609999999, 39.9207779999999],
     [-82.9984709999999, 39.887616],
     ...]
    
    def item_of_min_norm(target_coordinate):
        norms  = [np.linalg.norm(np.array(target_coordinate,float)-np.array(item,float), ord=1) for item in mylist]
        index_of_minimum = np.argmin(norms)
        minimum_item = mylist[index_of_minimum]
        return minimum_item
    
    
    # Use the new function
    closest_to_1_1 = item_of_min_norm([1.0,1.0])
    

    However, if I can guess your use case correctly, you probably want to use a KDTree. See https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html