Python:导入文件并转换为列表

har*_*lss 3 python file input list

我需要帮助导入文件并将每行转换为列表.

该文件的示例如下所示:

p wfgh 1111 11111 111111
287 48 0
65626 -1818 0
4654 21512 02020 0
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

Miz*_*zor 8

以下行将创建一个列表,其中每个项目都是一个列表.内部列表是一行分成"单词".

li = [i.strip().split() for i in open("input.txt").readlines()]
Run Code Online (Sandbox Code Playgroud)

我将您发布的代码段放入c:\ temp中的input.txt文件中并运行此行.输出是否与您想要的相似?

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']]
Run Code Online (Sandbox Code Playgroud)

  • 您不必使用readlines,open已经是一个迭代器.此外,imho,最好使用打开文件,然后使用您的创建. (2认同)

Jor*_*mer 0

如果您想要平面列表中的所有值,代码将如下所示:

ls=[]
for line in open( "input.txt", "r" ).readlines():
    for value in line.split( ' ' ):
        ls.append( value )
Run Code Online (Sandbox Code Playgroud)

如果你只想要列表中的行那么你可以停在 readlines() 处。