0

我有一个家庭作业,我收到了一份长约 10,000 行的文件。每行有 3 个元素,物种名称、纬度和经度。我需要编写一个函数,它返回在给定位置的特定距离内找到的动物数量,同时考虑 4 个参数:文件名、距离以及位置的纬度和经度。

在一个理想的世界里,我可以进入 shell,并使用文件名、任何距离和任何经纬度调用函数,并计算距离内的动物数量。

我已经成功地导入了文件,并且给了我一些代码示例来帮助计算距离并帮助将文件转换为列表。这是我到目前为止编写的代码:

def LocationCount(filename, distance, Lat1, Lon1):
FIn = open(filename, "r")
for Line in FIn:
    def LineToList(Line):
        Line = Line.rstrip()
    FIn.close()
    return Line.split("\t")

def CalculateDistance(Lat1, Lon1, Lat2, Lon2):

        Lat1 = float(Lat1)
        Lon1 = float(Lon1)
        Lat2 = float(Lat2)
        Lon2 = float(Lon2)

        nDLat = (Lat1 - Lat2) * 0.017453293
        nDLon = (Lon1 - Lon2) * 0.017453293

        Lat1 = Lat1 * 0.017453293
        Lat2 = Lat2 * 0.017453293

        nA = (math.sin(nDLat/2) ** 2) + math.cos(Lat1) * math.cos(Lat2) * (math.sin(nDLon/2) ** 2 )
        nC = 2 * math.atan2(math.sqrt(nA),math.sqrt( 1 - nA ))
        nD = 6372.797 * nC

return nD
4

1 回答 1

0

要将一条线分成几部分,您可以使用str.split(). 例如,要将空格分隔为 3 部分,您可以使用_, lat, lon = line.strip().split(' ')(下划线只是表示您不想使用第一部分的约定)。

这是一个更完整的例子。我根据 Pythons 样式约定(谷歌 Pythons PEP-8 样式指南)格式化了代码。

import math

def count_locations(filename, max_distance, source_lat, source_lon):
    counter = 0

    with open(filename) as f:
        for line in f:
            try:
                # try to split into 3 parts
                _, lat, lon = line.strip().split(' ')
            except ValueError:
                # cannot be split into 3 parts, so we skip this line
                continue

            try:
                # try to convert
                lat = float(lat)
                lon = float(lon)
            except ValueError:
                # cannot be converted to float, so we skip this line
                continue

            d = calculate_distance(source_lat, source_lon, lat, lon)
            if d <= max_distance:
                counter += 1

    return counter

def calculate_distance(lat_1, lon_1, lat_2, lon_2):
    n_d_lat = (lat_1 - lat_2) * 0.017453293
    n_d_lon = (lon_1 - lon_2) * 0.017453293

    lat_1 = lat_1 * 0.017453293
    lat_2 = lat_2 * 0.017453293

    n_A = (
            math.sin(n_d_lat / 2) ** 2
            + math.cos(lat_1) * math.cos(lat_2) * math.sin(n_d_lon / 2) ** 2
    )
    n_C = 2 * math.atan2(math.sqrt(n_A), math.sqrt(1 - n_A))
    n_D = 6372.797 * n_C

    return n_D

这对你有用吗?

于 2019-03-27T18:59:23.263 回答