【发布时间】:2010-07-29 22:23:01
【问题描述】:
我有一个相当大的元组列表,其中包含:
[('and', 44023), ('cx', 37711), ('is', 36777), ...]
我只想提取第一个字符串,所以上面列表的输出是:
and
cx
is
我如何编码(在某种程度上内置了可扩展性)?
【问题讨论】:
我有一个相当大的元组列表,其中包含:
[('and', 44023), ('cx', 37711), ('is', 36777), ...]
我只想提取第一个字符串,所以上面列表的输出是:
and
cx
is
我如何编码(在某种程度上内置了可扩展性)?
【问题讨论】:
[tup[0] for tup in mylist]
这使用列表推导。您也可以使用括号而不是外括号来使其成为生成器理解,因此评估会很懒惰。
【讨论】:
只是为 Matthew 提供解决方案的另一种方法。
tuples = [('and', 44023), ('cx', 37711), ('is', 36777) .... ]
strings, numbers = zip(*tuples)
如果您在某个时候决定希望将元组的两个部分放在不同的序列中(避免两个列表推导式)。
【讨论】:
如果你想得到准确的输出
and
cx
is
然后使用列表推导结合字符串join 方法像这样加入换行符
yourList = [('and', 44023), ('cx', 37711), ('is', 36777)]
print '\n'.join([tup[0] for tup in yourList])
【讨论】:
您可以在 for 循环中解压缩元组,如下所示:
for word, count in mytuple:
print "%r is used %i times!" % (word, count)
您可以在 Python 文档中看到它被广泛使用: http://docs.python.org/tutorial/datastructures.html#looping-technique
【讨论】: