在Python中获取列表中每个元组的第一个元素 [英] Get the first element of each tuple in a list in Python

查看:117
本文介绍了在Python中获取列表中每个元组的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

rows = cur.fetchall()res_list = []对于行中的行:res_list += [行[0]]

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

解决方案

使用列表理解:

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

以下是演示:

<预><代码>>>>行 = [(1, 2), (3, 4), (5, 6)]>>>[x[0] 代表 x 行][1, 3, 5]>>>

<小时>

或者,您可以使用解包代替 x[0]:

res_list = [x for x,_ in rows]

以下是演示:

<预><代码>>>>lst = [(1, 2), (3, 4), (5, 6)]>>>[x 代表 x,_ 在 lst][1, 3, 5]>>>

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

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?

解决方案

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.

这篇关于在Python中获取列表中每个元组的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆