Python,从文件到二维列表的数字

Python,从文件到二维列表的数字,python,list,io,Python,List,Io,我正在尝试将浮动从文本文件读入2d数组。该文件具有以下结构: 1.1 3.3 2.4576 0.2432 1.3 235.234 我希望将这些行读入2d列表,并以以下内容结束 data = [[1.1, 3.3] [2.4576, 0.2432] ... [1.3, 235.234]] 到目前为止,我的代码是: f = [] with open(str(i)) as fl: for line in fl: f.appen

我正在尝试将浮动从文本文件读入2d数组。该文件具有以下结构:

1.1
3.3
2.4576
0.2432
1.3
235.234
我希望将这些行读入2d列表,并以以下内容结束

data = [[1.1, 3.3]
        [2.4576, 0.2432]
        ...
        [1.3, 235.234]]
到目前为止,我的代码是:

f = []
with open(str(i)) as fl:
    for line in fl:
        f.append(float(line))
有没有一种简单而“好”的方法,不用使用很多帮助变量

(文件长度和数组大小(x*x)都是已知的)

这是因为行是通过调用fl.readline()来设置的,所以每次都会读取一行额外的内容。如果浮点转换失败,这显然会导致错误,但如果所有行的格式都正确,它将工作

您还可以执行以下操作:

f = fl.read().splitlines()
f = [f[x:x+2] for x in range(0,len(f),2)]
哪一个更像蟒蛇


Edited:
ValueError:如果将
for
循环与readline一起使用,则混合迭代和读取方法将丢失数据
被调用如果您使用的是NumPy,这可能更简单一些:

arr = np.loadtxt('arr.txt')
arr = arr.reshape((len(arr)//2, 2))
e、 g.从数字列中:
1。1.1 2. 2.2 ... 6.6.6
您可以得到:

array([[ 1. ,  1.1],
   [ 2. ,  2.2],
   [ 3. ,  3.3],
   [ 4. ,  4.4],
   [ 5. ,  5.5],
   [ 6. ,  6.6]])
如果您正在使用numpy(如果您正在做任何严肃的数值工作,您应该这样做),那么您可以重塑线性列表

import numpy as np

n = np.loadtxt(file_name)
n.reshape((-1,2))

重塑中的-1是让numpy算出尺寸大小

这可能是一个更通用的解决方案

finalList=[]
with open("demo.txt") as f:
    while True:
        try:
            innerList = [float(next(f).strip()) for x in xrange(2)]
            finalList.append(innerList)
        except StopIteration:
            break

print finalList
输出:

[[1.1, 3.3], [2.4576, 0.2432], [1.3, 235.234]]
这可以做到:

lines = [line.rstrip('\n') for line in open('file.txt', 'r')]

iterate_list = iter(lines)
for two_elem in iterate_list:
    print two_elem, next(iterate_list)
对于此文件内容:

1.1
3.3
2.4576
0.2432
1.3
235.234
您将获得:

1.1 3.3
2.4576 0.2432
1.3 235.234

ValueError:混合迭代和读取方法会丢失数据。这是正确的,我没有意识到这个错误。我已经相应地修改了代码
1.1 3.3
2.4576 0.2432
1.3 235.234