Re: [問題] 讀取檔案 字串存取問題

作者: apua (Apua)   2014-05-11 22:29:05
※ 引述《lingze (walkman)》之銘言:
: for i in open('file.txt', 'r'):
: print(i,end == '')
: 0 152 0 654 482 0 354 612 952 111
: 0 325 130 578 254 320 0 268 921 658
: 296 777 325 0
: ...
: 但是讀出來的檔案我想要儲存起來
: 想儲存成這樣:
: Matrix[0][0]=0
: Matrix[1][0]=152
: Matrix[1][1]=0
: Matrix[2][0]=654
: Matrix[2][1]=482
: Matrix[2][2]=0
s = open('file.txt').read()
L = list(map(int, s.split()))
I = filter(lambda i:L[i]==0, range(len(L)))
M = [L[a+1:b+1] for a,b in zip([-1]+I,I)] # Matrix
if __name__=='__main__':
from pprint import pprint
pprint(M)
'''
[[0],
[152, 0],
[654, 482, 0],
[354, 612, 952, 111, 0],
[325, 130, 578, 254, 320, 0],
[268, 921, 658, 296, 777, 325, 0]]
'''
資料量大時效率可能不會很高, 我只是當作練習, 請參考看看
作者: lingze (walkman)   2014-05-11 23:20:00
感謝大大~我參考一下:)

Links booklink

Contact Us: admin [ a t ] ucptt.com