如何在python中遍历列表列表?

Cha*_*gaD 13 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']]
Run Code Online (Sandbox Code Playgroud)

现在我需要遍历上面的列表并输出一个字符串列表,如下所示(没有原始列表中的数字)

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']
Run Code Online (Sandbox Code Playgroud)

mac*_*ing 32

完全按照您指定的方式执行的最简单的解决方案是:

documents = [sub_list[0] for sub_list in documents]
Run Code Online (Sandbox Code Playgroud)

这基本上等同于迭代版本:

temp = []
for sub_list in documents:
    temp.append(sub_list[0])
documents = temp
Run Code Online (Sandbox Code Playgroud)

然而,这并不是通过具有任意数量维度的多维列表进行迭代的一般方法,因为嵌套的列表推导/嵌套for循环可能会变得丑陋; 但是你应该安全地为2或3-d列表做这件事.

如果您确定需要展平3个以上的尺寸,我建议实施递归遍历功能,使所有非平面图层变平.


gfo*_*une 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!!')
Run Code Online (Sandbox Code Playgroud)

这是一种称为" 流量控制 " 的语言功能.

请注意,如果您只想要问题中给出的结果,那么提供机器向往的列表理解是最好的方法.

documents = [doc[0] for doc in documents]
Run Code Online (Sandbox Code Playgroud)

请注意,它会丢弃原始文档列表(您要覆盖原始变量),因此如果您想要获得第一列的副本以及原始列表的副本,请使用以下内容:

document_first_row = [doc[0] for doc in documents]
Run Code Online (Sandbox Code Playgroud)


小智 5

正如http://docs.python.org/library/operator.html#operator.itemgetter中所述,您也可以尝试使用

from operator import itemgetter
documents = map(itemgetter(0), documents)
Run Code Online (Sandbox Code Playgroud)

这应该比使用显式循环更快。