[Python] Find the closest latitude and longitude

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a small program and to improve efficiency, I need to be able to find the closest latitude and longitude in my array.

    Assume you have the following code:

    tempDataList = [{'lat': 39.7612992 , 'lon': -86.1519681},
    {"lat": 39.762241, "lon": -86.158436},
    {"lat": 39.7622292, "lon": -86.1578917}]

    tempLatList = []
    tempLonList = []

    for item in tempDataList:
    tempLatList.append(item['lat'])
    tempLonList.append(item['lon'])

    closestLatValue = lambda myvalue: min(tempLatList, key=lambda x: abs(x - myvalue))
    closestLonValue = lambda myvalue: min(tempLonList, key=lambda x: abs(x - myvalue))

    print(closestLatValue(39.7622290), closestLonValue(-86.1519750))


    The result I get is:

    (39.7622292, -86.1519681)


    What it should be is (in this example, the last object in the list)

    (39.7622292, -86.1578917)


    I know how to get a single value's closest cell but, I would like to make the lambda function to consider both values but I'm not entirely sure how. Help?

    Continue reading...

Compartilhe esta Página