Python:导入文件并转换为列表 [英] Python: Import a file and convert to a list

查看:104
本文介绍了Python:导入文件并转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个文件的例子如下所示:

  p wfgh 1111 11111 111111 
287 48 0
65626 -1818 0
4654 21512 02020 0

以p开头的第一行是一个标题,其余的是子句。
每个子句行必须以一系列至少两个整数开始,并以零结束

,这要归功于


  li = [i.strip()。split() readlines()] 

我把代码片段你发布到c:\temp的input.txt文件中,并运行这一行。输出类似于你想要的吗?

pre code $ \\ python
Python 3.1.1(r311 :74483,2009年8月17日,17:02:12)[win32
上的[MSC v.1500 32位(Intel)]键入help,copyright,credits或license
>>> print(input.txt)。readlines()])
[['p','wfgh','1111','11111' ,'111111'],['287','48','0'],['65626',' - 1818','0'],['4654','21512','02020','0 ']]


I need help with importing a file and converting each line into a list.

An example of the file would look like:

p wfgh 1111 11111 111111
287 48 0
65626 -1818 0
4654 21512 02020 0

The first line beginning with p is a header and the rest are clauses. Each clause line must begin with a series of at least two integers and finish with a zero

thanks in advance

解决方案

The following line will create a list where each item is a list. The inner list is one line thats split up into "words".

li = [i.strip().split() for i in open("input.txt").readlines()]

I put the code snippet you posted into a input.txt file in c:\temp and ran this line. Is the output similar to what you want?

C:\temp>python
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print([i.strip().split() for i in open("input.txt").readlines()])
[['p', 'wfgh', '1111', '11111', '111111'], ['287', '48', '0'], ['65626', '-1818', '0'], ['4654', '21512', '02020', '0']]

这篇关于Python:导入文件并转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆