【问题标题】:Combine two functions into one将两个功能合二为一
【发布时间】:2020-12-01 13:23:32
【问题描述】:

我有两个功能。其中一个返回一个列表,其中包含来自输​​入值的坐标子列表。另一个将这些坐标周围的缓冲区作为字典返回。我想简化这些功能,并可能以某种方式将它们组合起来。

buffer = 300

def coordinates(k_leht):
   x1 = int(k_leht[-3:]) * 1000
   y1 = int(k_leht[:3]) * 1000 + 6000000
   x2 = x1 + 1000
   y2 = y1 + 1000

   return [[x1, y1], [x2, y1], [x2, y2], [x1, y2], [x1, y1]]

def coordinates_buffer(k_leht):
   # Coordinates are created the same way as in the previous function
   x1 = int(k_leht[-3:]) * 1000
   y1 = int(k_leht[:3]) * 1000 + 6000000
   x2 = x1 + 1000
   y2 = y1 + 1000

   # Buffers around the coordinates
   x1_puhv = x1 - buffer
   y1_puhv = y1 - buffer
   x2_puhv = x2 + buffer
   y2_puhv = y2 + buffer

   return {'x1_puhv': x1_puhv, 'y1_puhv': y1_puhv, 'x2_puhv': x2_puhv, 'y2_puhv': y2_puhv}

【问题讨论】:

  • 只需将前几行分解成一个返回 x1、y1、x2、y2 的 extract_coordinates 函数?然后删除重复的部分并通过调用extract_coordinates(k_leht) 替换它们。

标签: python coordinates gis


【解决方案1】:

为避免无用的代码重复,您可以执行以下操作:

def coordinates_list_or_dict(k_leht, dict = False):
    x1 = int(k_leht[-3:]) * 1000
    y1 = int(k_leht[:3]) * 1000 + 6000000
    x2 = x1 + 1000
    y2 = y1 + 1000
   
    if (not dict): return [[x1, y1], [x2, y1], [x2, y2], [x1, y2], [x1, y1]]
    else:
        x1_puhv = x1 - buffer
        y1_puhv = y1 - buffer
        x2_puhv = x2 + buffer
        y2_puhv = y2 + buffer
        return {'x1_puhv': x1_puhv, 'y1_puhv': y1_puhv, 'x2_puhv': x2_puhv, 'y2_puhv': y2_puhv}

coordinates_buffer_or_list(k)       #=> return list
coordinates_buffer_or_list(k, True) #=> return dictionary

另一种解决方案是将前四行放在一个独立的函数中,并将其用作两个原始函数中的辅助函数。

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2013-07-07
    • 2023-03-10
    • 2016-07-27
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多