Python 将两个功能合并为一个
我有两个功能。其中一个返回一个列表,其中包含输入值的坐标子列表。另一个作为字典返回这些坐标周围的缓冲区。我想简化这些函数,并可能以某种方式将它们结合起来Python 将两个功能合并为一个,python,coordinates,gis,Python,Coordinates,Gis,我有两个功能。其中一个返回一个列表,其中包含输入值的坐标子列表。另一个作为字典返回这些坐标周围的缓冲区。我想简化这些函数,并可能以某种方式将它们结合起来 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
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
另一种解决方案是将前四行放在一个独立函数中,并将其用作两个原始函数中的辅助函数。只需将前几行分解成一个
提取坐标函数,返回x1,y1,x2,y2?然后移除重复的零件,并通过调用提取坐标(k\u leht)
替换它们。