5

所以就像标题说的我开始学习一些python并且我很难掌握这种技术。我需要完成的是读取一些数字并将它们存储在一个列表中。文本文件如下所示:

0 0 3 50

50 100 4 20

基本上这些是用于 python 的海龟制作形状的坐标和方向。我把那部分记下来了,唯一的问题是让它们以正确的格式出现。所以我不知道如何将这些数字从文件中获取到[ [0, 0, 3, 50], [50, 100, 4, 20] ] A 列表中,每个四个坐标都是那个大列表中的一个列表。

这是我的尝试,但正如我所说,我需要一些帮助 - 谢谢。

polyShape=[]
infile = open(name,"r")
num = int(infile.readline(2))
while num != "":
    polyShape.append(num)
    num = int(infile.readline(2))
infile.close()
4

6 回答 6

14
with open('data.txt') as f:
    polyShape = []
    for line in f:
        line = line.split() # to deal with blank 
        if line:            # lines (ie skip them)
            line = [int(i) for i in line]
            polyShape.append(line)

会给你

[[0, 0, 3, 50], [50, 100, 4, 20]]

这将适用于包含空行(或不包含)的文件。

with当您完成或遇到异常时,使用该构造会自动为您关闭文件。

于 2012-09-04T21:21:52.567 回答
4

假设您的输入文件中实际上没有空行:

with open(name, "r") as infile:
    polyShape = [map(int, line.split()) for line in infile]

说明:map(int, line.split())拆分每个line部分并将每个部分转换为int. 该[X for Y in Z]构造是一个列表推导式,它依次映射map文件的所有行并在列表中返回其结果。

如果你现在觉得这太复杂了,那么这map(int, line.split())是主要的带回家的信息。

于 2012-09-04T21:23:49.247 回答
2
with open('data.txt') as f:
    lis=[map(int,x.split()) for x in f if x.strip()]   # if x.strip() to skip blank lines

   #use list(map(int,x.split()))  in case of python 3.x

这是如何map()工作的:

>>> map(int,'1 2 3 4'.split())
[1, 2, 3, 4]
于 2012-09-04T21:23:31.923 回答
1

迭代文件将是最简单的方法:

poly_shape = []

with open(name, 'r') as handle:
    for line in handle:
        if not line.strip():
            continue  # This skips blank lines

        values = map(int, line.split())
        poly_shape.append(values)
于 2012-09-04T21:22:21.883 回答
1

单线:

[ [int(x) for x in line.split(' ')] for line in open(name,'r').readlines() if line.strip()]

但是这readlines部分可能不是一个好主意。

我很确定这[int(x) for x in ... ]map在其他建议的解决方案中使用更快。

编辑

感谢 Blender:不需要.readlines,这很酷,所以我们只有:

[ map(int, line.split()) for line in open(name,'r') if line.strip()]

我也使用map(int, )它,因为它实际上更快,而且你也可以使用line.split()代替line.split(' ').

于 2012-09-04T21:38:10.967 回答
0

我不建议使用append大型阵列。它比创建零数组并为其赋值慢 50 倍。

import numpy
fname = "D:\Test.txt";
num_lines = sum(1 for line in open(fname));
array = numpy.zeros((num_lines,4));
k = 0;
with open(fname, "r") as ins:
    for line in ins:
        a =[int(i) for i in line.split(' ')];;
         array[k,0:4] =a;
         k = k+1;
print(array)
于 2016-11-24T13:25:34.383 回答