[英]Extract string from a Tuple in python with psycopg2
我已經在python中編寫了一個web.py服務來訪問PostGres並獲取特定數據庫中的表名。
碼:
def GET(self,r):
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
tables = []
datasetID = web.input().dataSetID
cursor = conn.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
tablesWithDetails = cursor.fetchall()
print tablesWithDetails
for x in tablesWithDetails:
x.replace("(", "")
x.replace(")","")
tables.append(x)
print tables;
這將打印表如下,
[('acam_datasegregationdetails',), ('acam_datasegregationheader',), ('idn_accessinformation',), ('idn_b2cuseraccountmapping',), ('idn_b2cuserdevicemapping',), ('idn_b2cusers',), ('idn_roles',), ('idn_useraccountmapping')]
所需的輸出:
['acam_datasegregationdetails', 'acam_datasegregationheader', idn_accessinformation', 'idn_b2cuseraccountmapping', 'idn_b2cuserdevicemapping', 'idn_b2cusers', 'idn_roles', 'idn_useraccountmapping']
放下該循環並改為
tables = [t[0] for t in tablesWithDetails]
它將構建一個列表,其中包含結果集中每個元組的第一個元素。
甚至更簡單(也更便宜),如果您想要一個列表,則返回一個數組,該數組將被Psycopg調整為列表:
cursor.execute("""
select array_agg(relname)
from pg_class
where relkind='r' and relname !~ '^(pg_|sql_)';"
""")
tables = cursor.fetchall()[0][0]
問題是由於這段代碼
tables.append(x)
當您執行cursor.fetchall()
您將獲得一個元組列表
並且當您for x in tablesWithDetails:
您one tuple at a time
遍歷列表
因此,當執行tables.append(x)
時,您tables.append(x)
單個元素元組追加到列表中
要更改,您可以執行此表tables.append(x[0])
會附加元組的第一個元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.