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

时间:2012-02-05 16:59:47

标签: 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']

6 个答案:

答案 0 :(得分:32)

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

documents = [sub_list[0] for sub_list in documents]

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

temp = []
for sub_list in documents:
    temp.append(sub_list[0])
documents = temp

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

如果您确定需要展平超过3个尺寸,我建议您实施recursive traversal function以平整所有非平面图层。

答案 1 :(得分: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!!')

这是一种称为“flow control”的语言功能。

请注意,如果您只想要问题中给出的结果,那么提供list comprehension机器向往是最好的方法。

documents = [doc[0] for doc in documents]

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

document_first_row = [doc[0] for doc in documents]

答案 2 :(得分:4)

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

from operator import itemgetter
documents = map(itemgetter(0), documents)

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

答案 3 :(得分:1)

**编辑。谢谢DSM。这是错误的,因为它只是使列表变平。在OP想要忽略的文本之后,我没有注意到列表中的额外数据。

好的,我会让你变得非常轻松!

itertools.chain.from_iterable(documents)

正如其他人所说,这取决于你需要的最终行为。因此,如果您需要比这更复杂的东西,请使用递归遍历,或者如果您像我一样,请使用迭代遍历。如果你需要,我可以帮助你。

答案 4 :(得分:0)

您还可以使用zip with argument unpacking将“行”列表转换为列列表:

rows=[[1,'a','foo'],
      [2,'b','bar'],
      [3,'c','baz']]

columns=zip(*rows)
print columns
#[(1,2,3),
# ('a','b','c'),
# ('foo','bar','baz')]
print columns[0]
#(1,2,3)

*运算符将所有行作为zip

的单独参数传递
zip(*rows) == zip(row1,row2,row3,...)

zip获取所有行并使用每个列表中的一个项组装列

答案 5 :(得分:-1)

你可以使用numpy数组

例如

document = [['the quick brown fox', '2' ],['jumped over the lazy fox ','3']]

import numpy as np 
document = np.array(document)
document=document[:,0]
相关问题