2015-11-23 25 views
0

我已经在python中编写了一个web.py服务来访问PostGres并获取特定数据库中的表名。从Python中的元组中提取字符串psycopg2

CODE:

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'] 
+3

试试这个'tables.append(X [0])'如果这不起作用,你可以键入'type(x)' – The6thSense

+0

感谢它的工作 – Sajeetharan

+0

你知道吗它工作? – The6thSense

回答

3

丢弃循环,而不是在做

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] 
+0

那么如何运行'x.replace(“(”,“”)'和'x.replace(“)”,“”)'? –

+0

@Kevin据我所知,这是错误的。操作系统试图在返回的列表中“修复”或“投射”元组,假设它可以以某种方式被视为字符串。 –

+0

嗯......也许吧。然而元组没有'.replace()'方法。 Upvoted。 –

2

这个问题是由于这一段代码

tables.append(x) 

当你执行cursor.fetchall()你会得到的元组

的列表,当你做for x in tablesWithDetails:你被one tuple at a time

遍历列表所以,当你做tables.append(x)要附加一个单一的元素元组到列表

要改变,你可以做到这一点tables.append(x[0])它追加元组的第一个元素

+1

顺便说一句,怎么样'tables.extend(x)'? –

+0

@KevinGuan它肯定会在这种情况下工作,但如果元组中有很多元素,那么'extend'会附加所有元素 – The6thSense

+0

是的,只是认为在这种情况下使用'.extend'会更清晰:P –