首页 > 解决方案 > 使用 Psycopg 2 和 Python3 解析元组的结果列表

问题描述

如何使用Psycopg 2in从结果的每个索引中删除Python 3

下面是查询的结果——根据fetchall() ,据我所知,它是一个元组列表

import psycopg2
conn = psycopg2.connect(
    host="localhost", database="mydb_name", user="postgres", password="mydb_pwd);

# Activate connection cursor
cur = conn.cursor()
cur.execute(
    """
    SELECT
        (dmp).path[1],
        degrees(
            ST_Azimuth(
                (dmp).geom,
                ST_SetSRID(ST_MakePoint(391139.27, 5821816.69, 1.6), 25833)
            )
        ) AS azm 
    FROM 
    (SELECT ST_DumpPoints(geometry) AS dmp
     FROM surface_geometry
     Where cityobject_id=95) q
    """)
BuildingsAzimuth = cur.fetchall()

下面是结果的简短视图。

[(1, 218.030625163645),
 (1, 218.002520152173),
 (1, 218.002523848173),
 (1, 218.030628886541),
 (1, 218.030625163645),
 (1, 218.043760742269),
 (1, 218.030625163645),
 (1, 218.030628886541),
         .
         .
         .
 (1, 218.439989653911),
 (1, 218.002523848173),
 (1, 218.002520152173)]

先感谢您!

标签: pythonlistparsingpsycopg2

解决方案


列表推导结合解包元组是这里的方法:首先将结果分配给一个变量(在这种情况下我将它分配给 result_list),然后使用迭代两个元素(索引和值)的列表推导列表中的元组,并且只返回结果的值,而不是索引。

cleaned_result = [value for index, value in results_list] #Creates a new list with values you are interested in, without the indices.  
print(cleaned_result[0:3])

结果是:

[218.030625163645, 218.002520152173, 218.002523848173]

推荐阅读