Get the first element of each tuple in a list in Python

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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?

回答1:

Use a list comprehension:

res_list = [x[0] for x in rows] 

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)] >>> [x[0] for x in rows] [1, 3, 5] >>> 

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows] 

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)] >>> [x for x,_ in lst] [1, 3, 5] >>> 

Both methods practically do the same thing, so you can choose whichever you like.



回答2:

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


回答3:

You can use list comprehension:

res_list = [i[0] for i in rows] 

This should make the trick



回答4:

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) 


回答5:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!