如何在Python中遍历列表的列表?
我有一个这样的列表,其中包含多个子列表。
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']
7 个回答
5
在这个链接中有解释,你也可以试试下面这个方法:
from operator import itemgetter
documents = map(itemgetter(0), documents)
这个方法应该比用一个明确的循环要快。
8
如果你只是想在循环中遍历元素,并对这些元素进行一些操作(而不是问题中要求的特定结果),你可以使用一个简单的for循环。
for row in documents:
#do stuff with the row
print(row)
for column in row:
#do stuff with the columns for a particular row
print(column)
if(row[1] > 10):
print('The value is much too large!!')
这是一种叫做“流程控制”的语言特性。
需要注意的是,如果你只想得到问题中给出的结果,像machine yearning提供的那种列表推导式是最好的方法。
documents = [doc[0] for doc in documents]
请注意,这样做会丢弃你原来的文档列表(因为你是在覆盖原来的变量),所以如果你想保留第一列的副本以及原始列表的副本,可以使用以下方法:
document_first_row = [doc[0] for doc in documents]
35
最简单的方法来实现你所说的功能是:
documents = [sub_list[0] for sub_list in documents]
这基本上和下面的循环版本是一样的:
temp = []
for sub_list in documents:
temp.append(sub_list[0])
documents = temp
不过,这种方法并不是处理多维列表的通用方式,特别是当维度很多的时候,嵌套的列表推导式或者嵌套的循环可能会变得很复杂;不过对于二维或三维列表来说,这样做是没问题的。
如果你决定要处理超过三维的情况,我建议你实现一个递归遍历函数,这样可以把所有不平坦的层级都展开。