作者apua (Apua)
看板Python
标题Re: [问题] 读取档案 字串存取问题
时间Sun May 11 22:29:05 2014
※ 引述《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]]
'''
资料量大时效率可能不会很高, 我只是当作练习, 请参考看看
--
:wq
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.113.27.47
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/Python/M.1399818548.A.521.html
1F:推 lingze:感谢大大~我参考一下:) 05/11 23:20