【问题标题】:How to return back a list instead of tuple in psycopg2如何在 psycopg2 中返回列表而不是元组
【发布时间】:2016-03-22 07:41:09
【问题描述】:

我有以下问题

    cursor.execute(
    """
    SELECT transform(row_to_json(t)) FROM 
        (select * from table 
         where a = %s 
         and b = %s limit 1000) t;
    """
    , (a_value, b_value))

运行 records = cursor.fetchall() 将返回大小为 1 的元组列表。

有没有只返回一个列表的列表?

我问这个是因为我想将列表列表转换为一个 numpy 矩阵,并且循环将单例元组转换为列表很慢。

【问题讨论】:

  • 我非常怀疑 非常 对元组列表的迭代是否有任何显着放缓。

标签: python list postgresql numpy psycopg2


【解决方案1】:

当你有不止一行时,你可以使用下面的代码

result = [r[0] for r in cur.fetchall()]

【讨论】:

  • 完美。谢谢! ?
【解决方案2】:

作为一种快速修复,您可以返回一个数组:

cursor.execute("""
    select array_agg(transform(row_to_json(t)))
    from (
        select * from table 
        where a = %s and b = %s
        limit 1000
    ) t;
""", (a_value, b_value))

当 Psycopg 使 Postgresql 数组适应 Python 列表时,只需获取该列表:

records = cursor.fetchall()[0][0]

我想可以将cursor 子类化以返回列表而不是元组,但如果您不处理大型集合,我认为这不值得麻烦。

【讨论】:

    【解决方案3】:

    您也可以使用此代码

    result = cur.fetchall()
    x = map(list, list(result))
    x = sum(x, [])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2017-05-24
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      相关资源
      最近更新 更多