2013-07-22 17 views
0

我對Python很新,所以請原諒我對此事的有限瞭解。閱讀不同數量的列忽略Python中的特定元素

我的任務是從閱讀下面的文字文件中的每一行:

4 4738 6208 13891 14714 
5 848 1184 3227 6539 7139 
5 2748 8697 14917 15168 15751 
3 3568 10845 15435 
4 5136 5460 12082 15854 
4 3431 4571 10360 12118 
0 
3 1202 8022 13163 
4 2510 2603 7023 8035 
3 4886 7131 8428 
5 1090 1091 2613 6863 14302 
3 7747 9374 11169 
4 1360 2356 5122 11091 

不過,我想忽略每行(即所有的4S,5S,0和3秒的第一要素)並讀入其餘部分,將數字存儲到數組中。

我試過使用函數numpy.loadtxt,numpy.genfromtxt,但似乎有一個問題,列的數量變化的事實。我試圖通過閱讀10個字段並在沒有數字時插入「N」來優化這一點,但是我想知道是否有更有效的方法來處理事情。

感謝

布萊斯

回答

2

這應該給你所有的號碼(除第一列)在int小號

with open('path/to/file') as infile: 
    allNums = [[int(num) for num in line.strip().split()[1:]] for line in infile] 

列出的鋸齒狀2D清單如果你想關閉這個成爲int s的非鋸齒列表,則:

import itertools 
with open('path/to/file') as infile: 
    allNums = [[int(num) for num in line.strip().split()[1:]] for line in infile] 
nullValue = None 
allNums = list(itertools.izip.from_iterable(allNums, fillvalue=None)) # python 2.x 
# allNums = list(itertools.zip.from_iterable(allNums, fillvalue=None)) # python 3.x 
+0

恩,yea,像這樣...... – Jiminion

+0

strip()是否適用於製表符?就是想。 – Jiminion

+0

@Jim:AFAIK,['strip'殺死所有空白](http://docs.python.org/2/library/string.html#string.strip) – inspectorG4dget

0

閱讀整行,然後根據空白符分割。它應該返回每行的正確大小的列表。你將不得不忽略第一個元素。