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

时间:2014-03-14 17:48:17

标签: python python-2.7 syntax

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

[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]

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

rows = cur.fetchall()
res_list = []
for row in rows:
    res_list += [row[0]]

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

5 个答案:

答案 0 :(得分:161)

使用list comprehension

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

以下是演示:

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

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

res_list = [x for x,_ in rows]

以下是演示:

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

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

答案 1 :(得分:19)

如果您因某些原因不想使用列表理解,可以使用mapoperator.itemgetter

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>

答案 2 :(得分:19)

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

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)

答案 3 :(得分:11)

您可以使用列表理解:

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

这应该成功了

答案 4 :(得分:6)

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

c.f。 http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

有关为什么更喜欢对map等高阶函数进行理解的讨论,请转到http://www.artima.com/weblogs/viewpost.jsp?thread=98196

相关问题