Ouw*_*ang 4 python postgresql numpy psycopg2 list
我有以下查询
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))
Run Code Online (Sandbox Code Playgroud)
运行records = cursor.fetchall()
将返回大小为1元组的列表.
无论如何只返回一个列表列表?
我问这个是因为我想将列表列表转换为numpy矩阵,并且循环将单例元组转换为列表很慢.
Dim*_*iev 12
当您有多行时,可以使用以下代码
result = [r[0] for r in cur.fetchall()]
Run Code Online (Sandbox Code Playgroud)
作为快速修复,您可以返回一个数组:
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))
Run Code Online (Sandbox Code Playgroud)
当 Psycopg 使 Postgresql 数组适应 Python 列表时,只需获取该列表:
records = cursor.fetchall()[0][0]
Run Code Online (Sandbox Code Playgroud)
我想可以子类化cursor
以返回列表而不是元组,但是如果您不处理大型集合,我认为这不值得麻烦。
归档时间: |
|
查看次数: |
6188 次 |
最近记录: |