Find the closest match of a list in a list containing lists

后端 未结 2 867
攒了一身酷
攒了一身酷 2021-01-28 15:42

I have a list with two elements like this:

list_a = [27.666521, 85.437447]

and another list like this:

big_list = [[27.666519,          


        
相关标签:
2条回答
  • 2021-01-28 15:58

    From your question, it's hard to tell how you want to measure the distance, so I simply assume you mean Euclidean distance.

    You can use the key parameter to min():

    from functools import partial
    
    def distance_squared(x, y):
        return (x[0] - y[0])**2 + (x[1] - y[1])**2
    
    print min(big_list, key=partial(distance_squared, list_a))
    
    0 讨论(0)
  • 2021-01-28 16:08

    Assumptions:

    • You intend to make this type query more than once on the same list of lists
    • Both the query list and the lists in your list of lists represent points in a n-dimensional euclidean space (here: a 2-dimensional space, unlike GPS positions that come from a spherical space).

    This reads like a nearest neighbor search. Probably you should take into consideration a library dedicated for this, like scikits.ann.

    Example:

    import scikits.ann as ann
    import numpy as np
    k = ann.kdtree(np.array(big_list))
    indices, distances = k.knn(list_a, 1)
    

    This uses euclidean distance internally. You should make sure, that the distance measure you apply complies your idea of proximity.

    You might also want to have a look on Quadtree, which is another data structure that you could apply to avoid the brute force minimum search through your entire list of lists.

    0 讨论(0)
提交回复
热议问题