【问题标题】:Python array manipulation from psycopg2 PostgreSQL query来自 psycopg2 PostgreSQL 查询的 Python 数组操作
【发布时间】:2016-07-06 20:15:57
【问题描述】:

我正在使用 psycopg2 进行 psql 查询。

cur.execute("SELECT DISTINCT name FROM product")
result = cur.fetchall()
print(result)

[('product1',), ('product2',), ('product3',), ('product4',)]

我需要重新格式化这个数组来创建一个 API 端点。现在它是一个元组列表,其中元组的第二个值为空。一个简单的循环遍历就可以完成工作。

results=[]
for item in result:
    results.append(item[0])
print(results)

['product1','product2','product3','product4']

但是,此查询可能会变得相当大。遍历整个列表会增加查询的延迟,这似乎是不必要的。有没有办法在恒定时间内展平数组,或者以我需要的格式返回不同的 psycopg2 函数?

【问题讨论】:

    标签: python postgresql list psycopg2


    【解决方案1】:

    与数据库查询相比,转换列表所需的时间可以忽略不计。 但您无需亲自创建列表:

    cur.execute("SELECT DISTINCT name FROM product")
    result = [item for item, in cur]
    print(result) 
    

    【讨论】:

      【解决方案2】:

      在查询中聚合:

      query = '''
          select array_agg(distinct name)
          from product
      '''
      cursor.execute(query)
      rs = cursor.fetchall()[0][0]
      print rs
      

      输出:

      ['product1', 'product2', 'product3', 'product4']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-30
        • 2017-05-13
        • 1970-01-01
        • 2013-08-03
        • 2019-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多