I have a mysql call:
zip = 48326
cursor.execute ("""
select distinct(name)
from usertab
where zip= %s
""" , (zip))
result = cursor.fetchall()
The result is returned in a tuple that looks like this:
result = (('alan',), ('bob',), ('steve',), ('tom',))
But I need a list like this:
mylist= ['alan', 'bob', 'steve', 'tom']
So I process the tuple into a list like this:
mylist = []
for row, key in enumerate(result):
for col, data in enumerate(key):
mylist.append(data)
This code works, but I'd like a simpler way.
How can I fetch a mysql single column result directly into a list?
-
Thanks to Tadeck and Pawelmhm... I compacted my mysql fetch to this: mylist = [row[0] for row in cursor.fetchall()]panofish– panofish2013年07月11日 15:16:39 +00:00Commented Jul 11, 2013 at 15:16
2 Answers 2
Do it like that, using list comprehension:
mylist = [row[0] for row in result]
It will flatten your result and create list from it.
Another approach, without list comprehension:
from itertools import chain
mylist = list(chain.from_iterable(result))
It will flatten a result and convert it to list.
Comments
75 % of Python question on StackOverflow can be answered with the words: "list comprehension";)
Here is a solution using list comp:
>>> result = (('alan',), ('bob',), ('steve',), ('tom',))
>>> mylist = [i[0] for i in result]
>>> mylist
['alan', 'bob', 'steve', 'tom']
Please learn more about list comprehension here, it will save you a good deal of time.