将两个功能合二为一

Combine two functions into one

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

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}

为了避免无用的代码重复,您可以这样做:

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

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