简体   繁体   English

将两个功能合二为一

[英]Combine two functions into one

I have two functions.我有两个功能。 One of them returns a list which contains a sublists of coordinates from an input value.其中之一返回一个列表,其中包含来自输入值的坐标子列表。 The other returns a buffer around those coordinates as a dictionary.另一个返回围绕这些坐标的缓冲区作为字典。 I want to simplify those functions and maybe combine them in some way.我想简化这些功能,并可能以某种方式组合它们。

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}

To avoid useless repetition of codes you could do something like this:为了避免无用的重复代码,你可以这样做:

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

Another solution would be to put the four first lines in an independent function and use it as a helper function in the two original functions.另一种解决方案是将前四行放在一个独立的 function 中,并在两个原始函数中将其用作 helper function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM