繁体   English   中英

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

[英]How to iterate through a list of lists in 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']

准确执行您指定的操作的最简单解决方案是:

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维列表,您应该放心。

如果您决定需要平整3个以上的尺寸,我建议您实现一个递归遍历函数 ,该函数可以平整所有非平整的图层。

如果您只想遍历循环并使用元素做事(而不是问题中要求的特定结果),则可以使用基本的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!!')

这是一种语言功能,称为“ 流控制 ”。

请注意,如果您只想要问题中给出的结果,则提供的列表理解(例如提供的机器渴望)是最好的方法。

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

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

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

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

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

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

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

好吧,我会让您真的很轻松!

itertools.chain.from_iterable(documents)

正如其他人所说,这取决于您需要什么样的最终行为。 因此,如果您需要比这更复杂的内容,请使用递归遍历;如果您像我一样,请使用迭代遍历。 如果需要,我可以为您提供帮助。

您还可以将zip与参数解压缩一起使用,以将“行”列表转换为列列表:

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提取所有行并将列与每个列表中的一项组合在一起

你可以使用numpy数组

例如

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

import numpy as np 
document = np.array(document)
document=document[:,0]

这个问题已经死了,但是仍然知道另一种方法没有什么坏处:

 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']]

document = []
for first,*remaining in documents:
    document.append(first)

print(document)
['Human machine interface for lab abc computer applications',
 'A survey of user opinion of computer system response time', 
 'The EPS user interface management system'
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM