PSQL & Python = 如何返回 "elements" 的列表
PSQL & Python = how to have returned a list of "elements"
我有这个代码:
cur.execute("SELECT numbers FROM table")
supp = cur.fetchall()
for item in supp:
print item
并打印:
('one',)
('two',)
('three',)
我怎样才能拥有?
one
two
three
每个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']
try:
supp = cur.fetchall()
for item in supp:
print ' | '.join(item)
return "values printed"
except:
return "Something went wrong!"
我有这个代码:
cur.execute("SELECT numbers FROM table")
supp = cur.fetchall()
for item in supp:
print item
并打印:
('one',)
('two',)
('three',)
我怎样才能拥有?
one
two
three
每个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']
try:
supp = cur.fetchall()
for item in supp:
print ' | '.join(item)
return "values printed"
except:
return "Something went wrong!"