python - 如何将参数传递给 Python 函数?

标签 python function printing formula

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

但是,我不知道如何传递纬度和经度值,因为我替换了 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时会失败?

最佳答案

像这样使用它:

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

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

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

关于python - 如何将参数传递给 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826841/

相关文章:

python - PyQt 自定义数据结构

html - CSS HTML 页码

python - 在时间戳表上旋转的 Pandas 返回意外结果

javascript - 如何使用mpld3的LinkedBrush插件选择 "dump"点?

python selenium在连续3个网页上填写答案表

c++ - 将重载函数分配给函数指针作为默认值

具有两种类型参数的c++可变参数/可变参数函数

python - 如何在多处理函数中传递参数以及如何使用多处理列表?

asp.net - 最大限度地减少实现可打印报告的痛苦

python - 动态打印一行