动态迭代循环

时间:2018-11-16 11:38:01

标签: python python-3.x

我正在寻找一种更动态的方式来编写以下语句。

data = [r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13]] 

r代表我输入的响应数据,我将其用作数据并将其枚举到字典中。这可行,但是它太静态了。如果添加或删除了数据,则需要调整API代码以解决该问题。

处理此问题的直观方法是什么?下面是完整类的示例,以供参考。

class Pots(Resource):
    def get(self, store):
        print('USAGE: Received a request at POTS for Store ' + store )
        conn = sqlite3.connect('store-db.db')
        cur = conn.cursor()
        cur.execute('SELECT * FROM Pots WHERE StoreNumber like ' + store) 
        res = cur.fetchall()
        if not res:
            print("RESPONSE: No data was found for this request.")
            return('No data was found', 404)
        else:
            for r in res:
                column_names = ["StoreNumber", "ForwardOnFail", "HuntLine","FirePrimary","FireSecondary", "BurglarPrimary", "BurglarSecondary","BurglarTertiary", "DNR", "PassengerElevator", "FreightElevator", "Escalator1", "Escalator2","ShopperTrak"]
                data = [r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13]]         
                datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}
                return(datadict, 200)

编辑:请忽略任何SQL低效操作。我很欣赏建议,但我知道并且不打算在生产中使用它。仅用于测试。 :)

4 个答案:

答案 0 :(得分:1)

为此使用切片r[:14]

print(r[:14])

答案 1 :(得分:1)

常用列表理解:

 r = [1, 2, 3] 
 data = [r[0], r[1], r[2]]
 data
 [1, 2, 3]
 data = [r[i] for i in range(len(r)-1)]
 data
 [1, 2, 3]

答案 2 :(得分:1)

您可能正在寻找类似的东西。

请注意,我们正在使用sqlite3.Row行工厂,因此我们得到row.keys()

我也自由了

  • 修复该SQL注入漏洞
  • 添加limit子句(因为始终总是只返回一行)
  • 由于上述原因,
  • 使用fetchone()代替fetchall()

conn = sqlite3.connect("store-db.db")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute(
    "SELECT * FROM Pots WHERE StoreNumber like %s limit 1",
    (store,),
)
row = cur.fetchone()
if not row:
    raise NotImplementedError("...")
data_dict = {key: row[key] for key in row.keys()}

答案 3 :(得分:0)

让我们说您有这样的事情(使用python shell):

>>> column_names = ["a","b","c"]
>>> data = [1,2,3,4,5,6]
>>> {key:value for key,value in zip(column_names, data)}
{'a': 1, 'b': 2, 'c': 3}