在Python中的列表中获取每个元组的第一个元素

Cre*_*eak 110 python syntax python-2.7

SQL查询为我提供了一个元组列表,如下所示:

[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]
Run Code Online (Sandbox Code Playgroud)

我想拥有每个元组的所有第一个元素.现在我用这个:

rows = cur.fetchall()
res_list = []
for row in rows:
    res_list += [row[0]]
Run Code Online (Sandbox Code Playgroud)

但我认为可能有更好的语法来做到这一点.你知道更好的方法吗?

iCo*_*dez 172

使用列表理解:

res_list = [x[0] for x in rows]
Run Code Online (Sandbox Code Playgroud)

以下是演示:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用解压缩而不是x[0]:

res_list = [x for x,_ in rows]
Run Code Online (Sandbox Code Playgroud)

以下是演示:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>
Run Code Online (Sandbox Code Playgroud)

这两种方法实际上都做同样的事情,所以你可以选择你喜欢的.

  • @Creak - `x,_`只是使用元组解包.你是对的,关于这个的文档很难得到.我发现这个[链接](http://docs.python.org/release/1.5.1p1/tut/tuples.html),并且该[酮](http://www.developer.com/lang/other/article .php/630101/Learn-to-Program-using-Python-Unpacking-Tuples.htm #Introduction)应该解释它是如何工作的.另外,`_`只是一个普通变量.我本可以做'x,y`并得到相同的结果.但是,我没有,因为对于仅作为占位符的变量使用`_`是一种Python约定. (3认同)

lau*_*n91 23

实现此目的的功能方法是使用以下命令解压缩列表:

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)
Run Code Online (Sandbox Code Playgroud)


Jim*_*ian 20

如果由于某些原因不想使用列表推导,可以使用mapoperator.itemgetter:

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
Run Code Online (Sandbox Code Playgroud)


Rub*_*dez 11

您可以使用列表理解:

res_list = [i[0] for i in rows]
Run Code Online (Sandbox Code Playgroud)

这应该成功