python-3.x - 在python中,如何使用函数编程来生成泛型方法?

我想用函数编程来实现这一点,但是我不确定如何正确地做它。

这个方法得到一个dict对象,然后这个对象被转换为JSON ,变量将一个mid存储在外部API中,它必须在循环之前,否则将在每次迭代中调用API,然后在for循环中,遍历来自输入的数据.append(mid_current -bankMSell)


def margin_to_exchange_rate_sell(data):


 j = data.to_JSON()


 list_p = []


 mid = midrate.get_midrate(j["fromCurrency"][0])


 for idx, val in enumerate(j['toCurrency']):


 try:


 mid_current = 1/get_key(mid, j['toCurrency'][idx])


 bankMSell = float(j['sellMargin'][idx])


 list_p.append(mid_current - bankMSell)


 except Exception as e:


 list_p.append(0)


 print(str(e))



 return list_p



另一种方法:


def margin_to_exchange_rate_buy(data):


 j = data.to_JSON()


 list_p = []


 mid = midrate.get_midrate(j["fromCurrency"][0])


 for idx, val in enumerate(j['toCurrency']):


 try:


 mid_current = 1/get_key(mid, j['toCurrency'][idx])


 bankMSell = float(j['sellMargin'][idx])


 list_p.append(mid_current + bankMSell)


 except Exception as e:


 list_p.append(0)


 print(str(e))



 return list_p



时间:


def margin_to_exchange_rate_sell(data):


 return margin_to_exchange_rate(data, lambda m, b: m - b)



def margin_to_exchange_rate_buy(data):


 return margin_to_exchange_rate(data, lambda m, b: m + b)



def margin_to_exchange_rate(data, operation):


 j = data.to_JSON()


 list_p = []


 mid = midrate.get_midrate(j["fromCurrency"][0])


 for idx, val in enumerate(j['toCurrency']):


 try:


 mid_current = 1/get_key(mid, j['toCurrency'][idx])


 bankMSell = float(j['sellMargin'][idx])


 list_p.append(operation(mid_current, bankMSell))


 except Exception as e:


 list_p.append(0)


 print(str(e))



 return list_p



...