在Python中将文件内容复制到多维列表 [英] Copying file content to multi-dimensional list in Python
问题描述
我对将文件内容复制到Python中的多维列表感兴趣.
I am interested in copying the content of a file to a multidimensional List in Python.
文件类似于
b,30.83,0,u,g,w,v,1.25,t,t,01,f,g,00202,0,+
a,58.67,4.46,u,g,q,h,3.04,t,t,06,f,g,00043,560,+
a,24.50,0.5,u,g,q,h,1.5,t,f,0,f,g,00280,824,+
b,27.83,1.54,u,g,w,v,3.75,t,t,05,t,g,00100,3,+
b,20.17,5.625,u,g,w,v,1.71,t,f,0,f,s,00120,0,+
b,32.08,4,u,g,m,v,2.5,t,f,0,t,g,00360,0,+
我这里想要的是用逗号(','
)和换行符('\n'
,以跳转到下一个维度)分隔值...例如:-
What I want here is to separate the values with commas (','
) and newline ('\n'
, for jumping to the next dimension) ... for example:-
x[0][0]='b', x[0][1]=30.83, x[1][0]='a' ....
有什么建议吗?我尝试使用csv
,但是对于以后访问值来说太复杂了.有什么办法可以通过简单的文件方法来做到这一点?预先感谢.
Is there some suggestions? I tried to use csv
, but it's too complicated for me to access the values later. Is there any way I could manage to do that with the simple file methods? Thanks in advance.
推荐答案
使用列表理解(也从输入中删除换行符):
Use list comprehension (also remove newline from the input):
>>> x=[i.strip().split(',') for i in open("filename", 'r')]
对于问题中的输入,这将产生:
For the input in the question, this would produce:
>>> x
[['b', '30.83', '0', 'u', 'g', 'w', 'v', '1.25', 't', 't', '01', 'f', 'g', '00202', '0', '+'], ['a', '58.67', '4.46', 'u', 'g', 'q', 'h', '3.04', 't', 't', '06', 'f', 'g', '00043', '560', '+'], ['a', '24.50', '0.5', 'u', 'g', 'q', 'h', '1.5', 't', 'f', '0', 'f', 'g', '00280', '824', '+'], ['b', '27.83', '1.54', 'u', 'g', 'w', 'v', '3.75', 't', 't', '05', 't', 'g', '00100', '3', '+'], ['b', '20.17', '5.625', 'u', 'g', 'w', 'v', '1.71', 't', 'f', '0', 'f', 's', '00120', '0', '+'], ['b', '32.08', '4', 'u', 'g', 'm', 'v', '2.5', 't', 'f', '0', 't', 'g', '00360', '0', '+']]
>>> x[0][0]
'b'
>>> x[4][2]
'5.625'
这篇关于在Python中将文件内容复制到多维列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!