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

2024-04-29 12:30:14 发布

您现在位置: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']

Tags: of列表forlabmachinesysteminterfacesurvey
1条回答
网友
1楼 · 发布于 2024-04-29 12:30:14

如果只想遍历循环并使用元素(而不是问题中请求的特定结果)执行操作,可以使用basic 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楼 · 发布于 2024-04-29 12:30:14

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

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

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

网友
3楼 · 发布于 2024-04-29 12:30:14

最简单的解决方案是:

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来展平所有非展平层。

相关问题 更多 >