An SQL query gives me a list of tuples, like this:
[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]
I'd like to have all the first elements of each tuple. Right now I use this:
rows = cur.fetchall()
res_list = []
for row in rows:
res_list += [row[0]]
But I think there might be a better syntax to do it. Do you know a better way?
This question is related to
python
python-2.7
syntax
If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:
>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
res_list = [x[0] for x in rows]
c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
For a discussion on why to prefer comprehensions over higher-order functions such as map
, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.
You can use list comprehension:
res_list = [i[0] for i in rows]
This should make the trick
The functional way of achieving this is to unzip the list using:
sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)
(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)
Source: Stackoverflow.com