我有一张这样的单子。
documents = [['Human machine interface for lab abc computer applications','4'],
['A survey of user opinion of computer system response time','3'],
['The EPS user interface management system','2']]
现在我需要遍历上面的列表并输出一个字符串列表,如下所示(没有原始列表中的数字)
documents = ['Human machine interface for lab abc computer applications',
'A survey of user opinion of computer system response time',
'The EPS user interface management system']
如果只想遍历循环并使用元素(而不是问题中请求的特定结果)执行操作,可以使用basic for循环
这是一个称为“flow control”的语言特性。
注意,如果您只想得到问题中给出的结果,那么提供类似于list comprehension的机器渴望是最好的方法。
请注意,它会丢弃原始文档列表(您正在覆盖原始变量),因此,如果希望获得第一列的副本和原始列表的副本,请使用以下命令:
如http://docs.python.org/library/operator.html#operator.itemgetter中所述,您还可以尝试使用
这应该比使用显式循环更快。
最简单的解决方案是:
这基本上等同于迭代版本:
然而,这并不是一种遍历具有任意维数的多维列表的通用方法,因为嵌套列表理解/嵌套for循环可能会变得难看;但是,对于2或3-d列表,这样做应该是安全的。
如果您确实决定需要展平超过3个维度,我建议实现一个recursive traversal function来展平所有非展平层。
相关问题 更多 >
编程相关推荐