从2D坐标识别区域的最快方法

时间:2014-03-17 15:58:11

标签: python if-statement coordinates

我有以下代码:

def findRegion(lat,lon):
    '''Gets a lat between -90,90 and a lon between -180,180 and returns a character'''
    if lat >= 50:
        y='ABCD'
    elif lat >= 0:
        y='EFGH'
    elif lat <= -50:
        y='MNOP'
    else:
        y='IJKL'

    if lon <= -90:
        x='AEIM'
    elif lon <= 0:
        x='BFJN'
    elif lon <= 90:
        x='CGKO'
    else:
        x='DHLP'

    for c in y:
        if c in x:
            return c

此函数获取两个坐标并返回显示here的16个扇区代码之一。代码工作得很好,但它会被调用很多次,所以我正在寻找最快的解决方案。任何建议都非常感谢。

2 个答案:

答案 0 :(得分:3)

这应该通过使用x和y来查找一维字符串中的区域来加速该过程。由于使用了钳子,实际上可能会变慢。

clamp = lambda n, minimum, maximum: max(min(maximum, n), minimum)

def a(lat, lon):
    ## get lat, lon sections
    sec_lat = clamp((lat+90)/45,0,3)
    sec_lon = clamp((lon+180)/90,0,3)

    ## convert two values into a 1 dimensional list value
    sec = sec_lat*4 + sec_lon

    return "MNOPIJKLEFGHABCD"[sec]

答案 1 :(得分:1)

这会通过跳过双倍来提高速度(因为在每个循环中只有4次迭代,因此在16位字符比较的最差情况下,这实际上是微不足道的)。虽然,我认为主要的改进在于可读性,这通常更为重要。

def findRegion(lat, lon):
    regions = ( ('A', 'B', 'C', 'D'), ('E', 'F', 'G', 'H'), ('I', 'J', 'K', 'L'), ('M', 'N', 'O', 'P'))

    lat_index = 0;
    if lat >= 50:
        lat_index = 0
    elif lat >= 0:
        lat_index = 1
    elif lat <= -50:
        lat_index = 2
    else:
        lat_index = 3

    lon_index = 0
    if lon <= -90:
        lon_index = 0
    elif lon <= 0:
        lon_index = 1
    elif lon_index <= 90:
        lon_index = 2
    else:
        lon_index = 3

    return regions[lat_index][lon_index]

print findRegion(-45, 50)
相关问题