2012-02-05 67 views
11

我有這樣的列表清單。如何迭代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'] 
+4

在Python中沒有數組,你的意思' list's。 – juliomalegria 2012-02-05 19:43:39

回答

27

做最簡單的解決方案,正是你規定是:

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,它將所有非平面層展平。

+4

+1列表解析 – Zenon 2012-02-05 17:06:51

+0

謝謝:)它的工作。 – ChamingaD 2012-02-05 17:36:15

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] 
+0

感謝您的幫助:) – ChamingaD 2012-02-05 17:36:40

2

**編輯。感謝帝斯曼。這是錯誤的,因爲它只是壓扁了列表。在OP想要忽略的文本之後,我沒有注意到列表中的額外數據。

好吧我會讓你真的很容易!

itertools.chain.from_iterable(documents) 

正如其他人所說,這取決於你需要什麼樣的最終行爲。所以,如果你需要比這更復雜的東西,使用遞歸遍歷,或者如果你像我一樣,使用迭代遍歷。如果你需要的話,我可以幫你。

+0

這將扁平化列表,而不是提取第一個元素。確實是 – DSM 2012-02-05 17:22:49

+0

。我誤解了他想要的行爲。提供遍歷幫助仍然開放 – KobeJohn 2012-02-05 17:30:35

+0

感謝您的幫助:) – ChamingaD 2012-02-05 17:36:45

0

您也可以使用壓縮與參數拆包改造「行」的列表爲列的列表:

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(*rows) == zip(row1,row2,row3,...) 

拉鍊通吃的行和列裝配有一個項目從每個列表

0

你可以使用numpy的陣列

例如

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

import numpy as np 
document = np.array(document) 
document=document[:,0] 
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' 
]