【问题标题】:How do I pass parameters to a Python function?如何将参数传递给 Python 函数?
【发布时间】:2013-05-30 02:07:20
【问题描述】:

我正在尝试使用网上找到的这个函数来计算地球上两个经纬度点之间的距离。

但是,我不知道如何传递我的纬度和经度值,因为我替换了 lat1lon1lat2lon2,并且每次都会出错。

我在哪里输入我想要的纬度和经度值?

import math

def distance(origin, destination):
    lat1, lon1 = origin
    lat2, lon2 = destination
    radius = 6371 # km

    dlat = math.radians(lat2-lat1)
    dlon = math.radians(lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c

    return d

编辑: 例如,如果我有

lat1 = 20 and lon1 = 100 
lat2 = 30 and lon2 = 110 

为什么我用函数中的数字替换 lon1 会失败?

【问题讨论】:

    标签: python function printing formula


    【解决方案1】:

    像这样使用它:

    distance((lat1, lon1), (lat2, lon2))
    

    请注意,该函数接收两个二元素元组(或两个二元素列表,它们是相同的)作为参数,每个元组代表一个(纬度,经度)对。等效:

    origin = (lat1, lon1)
    destination = (lat2, lon2)
    distance(origin, destination)
    

    【讨论】:

    • 我仍然对如何使用它感到困惑,因为我在尝试执行时不断出错。说我的 lat1 = 20 和我的 lon1 = 100 和 lat2 = 30 和 lon2 = 110 然后我将如何将这些数字放入您的方程式和整个函数中。谢谢
    • 像这样:distance((20, 100), (30, 200))
    • Lopez 请你编辑上面的初始代码,因为我正在尝试你的,它根本不起作用,因为当我输入元组时,我一直收到无效的语法,如你所示
    • 它对我有用,就像我上面写的一样。你一定是做错了什么,但我的回答是正确的,我什至用例子测试过,它返回9818.324994648268
    • 谢谢我现在的工作它确实是一个空格错误 Oscar :)
    【解决方案2】:

    您可以通过为每个元组传递元组来使用命名参数调用它,例如:

    distance(origin=origin_tuple, destination=dest_tuple)
    

    在哪里

    origin_tuple = (origin_lat , origin_long)
    dest_tuple = (dest_lat , dest_long)
    

    【讨论】:

      猜你喜欢
      • 2015-01-23
      • 1970-01-01
      • 2020-08-26
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      相关资源
      最近更新 更多