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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22412258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:54:51  来源:igfitidea点击:

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

pythonpython-2.7syntax

提问by Creak

An SQL query gives me a list of tuples, like this:

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

[(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?

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

采纳答案by Creak

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

或者,您可以使用解包而不是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.

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

回答by Ruben Bermudez

You can use list comprehension:

您可以使用列表理解:

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

This should make the trick

这应该是诀窍

回答by Aegis

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

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

参见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.

有关为什么更喜欢推导式而非高阶函数(例如 )的讨论map,请访问http://www.artima.com/weblogs/viewpost.jsp?thread=98196

回答by Jimilian

If you don't want to use list comprehension by some reasons, you can use mapand operator.itemgetter:

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

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

回答by rbonallo

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)

(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)