2012-08-07 129 views

回答

3

讓我們假設該文件名爲spam.txt

$ cat spam.txt 
a,b,c,d, 
1,1,2,3, 
4,5,6,7, 
1,2,5,7, 
6,9,8,5,  

使用list comprehensionszip()內置的功能,你可以寫一個程序,如:

>>> with open('spam.txt', 'r') as file: 
...  file.readline() # skip the first line 
...  rows = [[int(x) for x in line.split(',')[:-1]] for line in file] 
...  cols = [list(col) for col in zip(*rows)] 
... 
'a,b,c,d,\n' 
>>> rows 
[[1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5]] 
>>> cols 
[[1, 4, 1, 6], [1, 5, 2, 9], [2, 6, 5, 8], [3, 7, 7, 5]] 

此外,zip(*rows)是基於在unpacking argument lists,解壓縮列表或元組,以便其元素可以作爲單獨的位置參數傳遞給函數。換句話說,zip(*rows)減少到zip([1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5])

編輯:

這是基於NumPy的參考版本:

>>> import numpy as np 
>>> with open('spam.txt', 'r') as file: 
...  ncols = len(file.readline().split(',')) - 1 
...  data = np.fromiter((int(v) for line in file for v in line.split(',')[:-1]), int, count=-1) 
...  cols = data.reshape(data.size/ncols, ncols).transpose() 
... 
>>> cols 
array([[1, 4, 1, 6], 
     [1, 5, 2, 9], 
     [2, 6, 5, 8], 
     [3, 7, 7, 5]]) 
+0

是的,這是很好的解釋...因爲我處理大型文本文件,列表「行」或「列」的大小將會很大,上面的代碼所佔用的RAM大小約爲1.4 GB,對於500 MB的輸入文件。有沒有任何優化的方式來做到這一點..? – 2012-08-07 06:41:16

+0

@JagannathKs這取決於你的目標。最後你會怎麼處理這些列呢? – dkim 2012-08-07 06:59:52

+0

我會得到2個這樣的列爲2個不同的文件,並根據一定的標準來處理它們....任何方式生病嘗試優化它。感謝您的回覆 – 2012-08-07 07:30:59

0

可以嘗試以下代碼:

from numpy import* 

x0 = [] 
for line in file('yourfile.txt'): 
    line = line.split() 
    x = line[1] 
    x0.append(x) 

for i in range(len(x0)): 
print x0[i] 

在此,第一列被附加到X0 []。您可以以類似的方式追加其他列。

+0

爲什麼'這裏需要numpy'? – Kos 2012-08-07 05:54:16

+0

numpy包含一個強大的N維數組對象,也可以用作通用數據的高效多維容器。可以定義任意數據類型。這使numpy能夠與各種數據庫無縫並快速地集成。 – 2012-08-07 05:56:58

+3

你的例子在哪裏使用? – Kos 2012-08-07 06:24:30