如何从元组列表中提取第一项

2024-04-27 04:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当大的元组列表,其中包含:

[('and', 44023), ('cx', 37711), ('is', 36777), ...]

我只想提取第一个字符串,因此上面列表的输出为:

and
cx
is

我该如何编写代码(在某种程度上内置了扩展性)


Tags: and字符串代码列表is内置元组cx
3条回答
[tup[0] for tup in mylist]

这使用列表理解。您还可以使用圆括号而不是外括号使其成为生成器,所以求值将是惰性的

只是为Matthew的解决方案提供了一种替代方法

tuples = [('and', 44023), ('cx', 37711), ('is', 36777) .... ]
strings, numbers = zip(*tuples)

如果您在某个时刻决定要将元组的两个部分都放在单独的序列中(避免两个列表的理解)

如果你想得到准确的输出

and
cx
is

然后结合使用一个列表理解和stringsjoin方法来连接换行符,如下所示

yourList = [('and', 44023), ('cx', 37711), ('is', 36777)]
print '\n'.join([tup[0] for tup in yourList])

相关问题 更多 >