2012-09-27 41 views
1

我有看起來像這樣的文本文件的一些數據:更有效的方法來解析python中的矩陣?

1895723957 
8599325893 
5723857831 
5025852920 

,我想將它解析爲Python中列表的列表,所以輸出

[[1, 8, 9, 5, 7, 2, 3, 9, 5, 7], [8, 5, ... 

權現在,我有

data = open('file.txt') 
rows = [str(line).strip() for line in data] 
matrix=[] 
for r in rows: 
    matrix.append(list(r)) 

但是有沒有不同的方法來做到這一點,比如使用更少的代碼行或利用理解?

我試着環顧四周,但我不能完全確定哪些關鍵字用在這裏...

謝謝了!

回答

1

我想嘗試這樣的事:

with open('file.txt', 'r') as handle: 
    matrix = [map(int, line.strip()) for line in handle] 
+0

非常感謝!這工作,但我不得不使用map(int,line.strip())。我會研究map()的工作方式。 – acs

+0

如果你使用'rstrip'而不是'strip',你可能會削減一秒左右。 – Blender

0

我與內涵玩弄後,想出瞭如下方式:

data = open('file.txt') 
matrix = [[int(c) for c in row.rstrip()] for row in data] 

rstrip得益於以上攪拌機。

相關問題