Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从文件读入列表_Python_File Io - Fatal编程技术网

Python:从文件读入列表

Python:从文件读入列表,python,file-io,Python,File Io,我想让我的程序从一个.txt文件中读取数据,该文件中的数据行排列如下: NUM NAME。如何将它的行读入一个列表,使每一行都成为列表的一个元素,并且每个元素的前两个值都是int,其余三个值都是string 因此,文件的第一行:123joe Main Sto应该变成lst[0]=[1,23,“Joe”,“Main”,“Sto”] 我已经有了这个,但它并不完美,我相信一定有更好的方法: read = open("info.txt", "r") line = read.readlines() tex

我想让我的程序从一个.txt文件中读取数据,该文件中的数据行排列如下:
NUM NAME
。如何将它的行读入一个列表,使每一行都成为列表的一个元素,并且每个元素的前两个值都是int,其余三个值都是string

因此,文件的第一行:
123joe Main Sto
应该变成
lst[0]=[1,23,“Joe”,“Main”,“Sto”]

我已经有了这个,但它并不完美,我相信一定有更好的方法:

read = open("info.txt", "r")
line = read.readlines()
text = []
for item in line:
    fullline = item.split(" ")
    text.append(fullline)
在不带参数的情况下使用可自动折叠并删除空白,然后将
int()
应用于前两个元素:

with open("info.txt", "r") as read:
    lines = []
    for item in read:
        row = item.split()
        row[:2] = map(int, row[:2])
        lines.append(row)
注意这里我们直接在文件对象上循环的内容,无需先将所有行读入内存。

使用无参数自动折叠并删除空白,然后将
int()
应用于前两个元素:

with open("info.txt", "r") as read:
    lines = []
    for item in read:
        row = item.split()
        row[:2] = map(int, row[:2])
        lines.append(row)
with open(file) as f:
    text = [map(int, l.split()[:2]) + l.split()[2:] for l in f]

注意这里我们直接在file对象上循环的内容,不需要先将所有行读入内存。

我认为执行
row.strip().split()
会更好help@RemcoGerlich:不,因为没有参数的
.split()。非常感谢。很有魅力,谢谢。我来自codecademy,你能推荐一些我可以从Python中学到更多的东西吗?(为了能够独立完成你的答案)继续阅读Python的内容,继续编码。有很多东西可以让你继续前进。我不能推荐更具体的东西;我已经编写Python代码15年了,我已经很久没有读过任何Python书籍了。我想做
row.strip().split()
help@RemcoGerlich:不,因为没有参数的
.split()。非常感谢。很有魅力,谢谢。我来自codecademy,你能推荐一些我可以从Python中学到更多的东西吗?(为了能够独立完成你的答案)继续阅读Python的内容,继续编码。有很多东西可以让你继续前进。我不能推荐更具体的东西;我编写Python已经15年了,我已经很久没有读过任何Python书籍了。
with open(file) as f:
    text = [map(int, l.split()[:2]) + l.split()[2:] for l in f]