Python 引用数组

Python 引用数组,python,python-2.7,Python,Python 2.7,我的代码当前将数据写入如下文件: 1 1.64 -0.76 2 2.365 0.39 3 6.48 0.88 4 10.45 -0.75 5 12.12 -0.33 6 15.39 0.85 7 19.32 -0.73 8 24.24 0.92 9 26.73 0.35 10 28.18 -0.75 11 33.14 0.85 12 37.02 -0.74 13 37.19 -0.35 14 4

我的代码当前将数据写入如下文件:

1   1.64    -0.76
2   2.365   0.39
3   6.48    0.88
4   10.45   -0.75
5   12.12   -0.33
6   15.39   0.85
7   19.32   -0.73
8   24.24   0.92
9   26.73   0.35
10  28.18   -0.75
11  33.14   0.85
12  37.02   -0.74
13  37.19   -0.35
14  41.9    0.9
15  45.81   -0.85
16  50.48   0.34
17  50.71   0.84
18  54.61   -0.71
19  59.53   0.88
现在我想引用它进行操作,例如只打印第3列。我试过:

f = open('./gilly.txt', 'r')
print f[2]

但它不起作用。。。建议?

文件只能逐行读取,因此您必须全部读取。如果只需要一列,可以执行以下操作:

with open('gilly.txt') as myfile:
    third = [float(line.split()[2]) for line in myfile]
(请注意转换为<代码>浮点)

或者,您可以将整个文件读取到列表列表中:

with open('gilly.txt') as myfile:
    lists = [line.split() for line in myfile]
有时您根本不需要建立列表:

with open('gilly.txt') as myfile:
    tuples = (map(float, line.split()) for line in myfile)

这应该可以让您开始了。

要将整个文件读入数据结构,请执行以下操作:

data = [x.strip ().split () for x in open ('gilly.txt') ]
还是去拿彩车

data = [ [float (y) for y in x.strip ().split () ] for x in open ('gilly.txt') ]