PSQL& Python =如何返回“元素”列表

时间:2016-07-07 13:21:58

标签: python sql postgresql python-2.7 psql

我有这段代码:

cur.execute("SELECT numbers FROM table")
supp = cur.fetchall()
for item in supp:
    print item

并打印:

('one',)
('two',)
('three',)

我怎么能拥有?

one
two
three

2 个答案:

答案 0 :(得分:1)

每个item对应于查询结果的一行,每行由元组表示。如果你想获得每个元组的第一项,你可以unpack them in the for loop

for value, in supp:
    print(value)

或者,你也可以通过索引获得第一项

for row in supp:
    print(row[0])

您还可以将它们放入包含list comprehension

的列表中
values = [value for value, in supp]

演示:

>>> supp = [('one',), ('two', ), ('three', )]
>>> for value, in supp:
...     print(value)
... 
one
two
three
>>> [value for value, in supp]
['one', 'two', 'three']

答案 1 :(得分:0)

try:
    supp = cur.fetchall()
    for item in supp:
        print ' | '.join(item)
    return "values printed"
except:
    return "Something went wrong!"

这里答案是...... plz删除这篇文章:)