删除烧瓶中列表中的空字典或列表

时间:2019-02-26 17:15:34

标签: python

我在python flask中有这段代码,可以很容易地在json中返回结果。

    for c2 in range(0, len(x1)):
        cur = conn.cursor()
        cur.execute('SELECT tbl_assigned_stores.tblstoreid, tbl_users.tbluserid, CONCAT(tbl_users.firstname, tbl_users.lastname) AS mechandiser, tbl_single_role.userrole AS user_role FROM tbl_users INNER JOIN tbl_assigned_stores ON tbl_assigned_stores.tbluserid = tbl_users.tbluserid INNER JOIN tbl_single_role ON tbl_single_role.tblsingleroleid = tbl_users.tblsingleroleid WHERE tbl_users.tblsingleroleid = 2  AND tbl_assigned_stores.tblstoreid = '+tbl_hierarchy2[c2]+'' )
        da2 = [dict(((cur.description[i][0]), value)
                for i, value in enumerate(row)) for row in cur.fetchall()]

        print(da2)
return da2[0]

返回错误,索引超出范围,因为有2个空列表。这是控制台中的结果

[{'tblstoreid': 439, 'tbluserid': 40, 'mechandiser': 'Charmain Miranday', 'user_role': 'Merchandiser (R)'}]
[]
[{'tblstoreid': 509, 'tbluserid': 79, 'mechandiser': 'Argie Alfelor', 'user_role': 'Merchandiser (R)'}]
[{'tblstoreid': 513, 'tbluserid': 72, 'mechandiser': 'Jomel Canopa', 'user_role': 'Merchandiser (R)'}]
[{'tblstoreid': 517, 'tbluserid': 72, 'mechandiser': 'Jomel Canopa', 'user_role': 'Merchandiser (R)'}]
[{'tblstoreid': 532, 'tbluserid': 70, 'mechandiser': 'Jessie Penaflorida', 'user_role': 'Merchandiser (R)'}]
[]

如何删除这些空列表?我试过filter([],da2)和filter(None,da2),但是没有运气。请帮助我,谢谢。

1 个答案:

答案 0 :(得分:1)

尝试一下-它会为每个结果创建一个单独的列表,并在其中一行,然后您可以在最后返回:

da2 = []
for c2 in range(0, len(x1)):
    cur = conn.cursor()
    cur.execute('SELECT tbl_assigned_stores.tblstoreid, tbl_users.tbluserid, CONCAT(tbl_users.firstname, tbl_users.lastname) AS mechandiser, tbl_single_role.userrole AS user_role FROM tbl_users INNER JOIN tbl_assigned_stores ON tbl_assigned_stores.tbluserid = tbl_users.tbluserid INNER JOIN tbl_single_role ON tbl_single_role.tblsingleroleid = tbl_users.tblsingleroleid WHERE tbl_users.tblsingleroleid = 2  AND tbl_assigned_stores.tblstoreid = '+tbl_hierarchy2[c2]+'' )
    da2.append([dict(((cur.description[i][0]), value)
            for i, value in enumerate(row)) for row in cur.fetchall()])

返回时(循环外),您可以仅使用return da2返回整个列表,包括空结果,也可以仅返回return [row for row in da2 if row]的非空行。

此外,不建议使用字符串连接来构建查询:

cur.execute('SELECT... AND tbl_assigned_stores.tblstoreid = '+tbl_hierarchy2[c2]+'')

使用参数化查询来缓解SQL injection漏洞:

cur.execute('SELECT... AND tbl_assigned_stores.tblstoreid = ?', (tbl_hierarchy2[c2],))

根据所使用的数据库,语法可能与上述语法略有不同,但是无论如何建议均适用。