【问题标题】:How to make my code more simplified?如何让我的代码更简化?
【发布时间】:2017-05-26 09:27:23
【问题描述】:

谁能帮我简化我的代码..我用相同的功能做了5个不同的功能,唯一的区别是列表中的名称将显示信息。

请告诉我如何缩短它。

我的代码:

def country():
   cur = mysql.connection.cursor()
   cur.callproc('spGetAllCountry')
   data = cur.fetchall()

   country_list=[];
   for country in data:
       i = {
        'Name' : country[2],
        'Code' : country[0],
        'Description' : country[1]
        }
       country_list.append(i)

   return jsonify(country_list)

def currency():
   cur = mysql.connection.cursor()
   cur.callproc('spGetAllCurrency')
   data = cur.fetchall()

   currency_list=[];
   for currency in data:
      i = {
        'Name' : currency[2],
        'Code' : currency[0],
        'Description' : currency[1]
        }
      currency_list.append(i)

   return jsonify(currency_list)

def paymentbrand():
   cur = mysql.connection.cursor()
   cur.callproc('spGetPaymentbrand')
   data = cur.fetchall()

   paymentbrand_list=[];
   for paymentbrand in data:
      i = {
        'Name' : paymentbrand[2],
        'Code' : paymentbrand[0],
        'Description' : paymentbrand[1],
                    'Payment Code' : paymentbrand[3]
        }
      paymentbrand_list.append(i)

   return jsonify(paymentbrand_list)

def paymentmode():
   cur = mysql.connection.cursor()
   cur.callproc('spGetPaymentmode')
   data = cur.fetchall()

   paymentmode_list=[];
   for paymentmode in data:
       i = {
        'Name' : paymentmode[2],
        'Code' : paymentmode[0],
        'Description' : paymentmode[1]
        }
       paymentmode_list.append(i)

   return jsonify(paymentmode_list)

【问题讨论】:

  • 为什么是 Java 标签?
  • 你应该把这个发到codereview.stackexchange.com
  • 你能修正你的缩进吗?
  • 完成编辑@Nuageux
  • @RichardTao,仍然有一些错误(在 def 之外返回)。您还应该考虑 Steve Smith 的评论。

标签: python python-2.7 python-3.x function


【解决方案1】:

试试这个:

def get_data(func_name, value_idx_map):
    cur = mysql.connection.cursor()
    cur.callproc(func_name)
    dataArr = cur.fetchall()

    res=[]
    for item in dataArr:
        v = { key: item[idx] for key, idx in value_idx_map.items()}
        res.append(v)
    return pprint.pprint(res)

common_idx = {'Name': 2, 'Code': 0, 'Description': 1}

get_data('spGetAllCountry', common_idx)
get_data('spGetAllCurrency', common_idx)
get_data('spGetPaymentmode', common_idx)

common_idx['Payment Code'] = 3
get_data('spGetPaymentbrand', common_idx)

【讨论】:

  • 谢谢兄弟 :) 我试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
相关资源
最近更新 更多