在 Python 中读取文件后尝试创建 x 和 y 值数组

Trying to create an array of x and y values after reading file in Python

最初我只是简单地使用 MatPlotLib 来绘制这些点,然后像这样阅读它们:

with open("data1.txt") as f:
    samples = f.read()

samples = samples.split('\n')

x = [row.split(' ')[0] for row in samples]
y = [row.split(' ')[1] for row in samples]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.plot(x,y, 'ro')

但是,我现在意识到我需要将所有这些信息存储在某种数组中以备后用。我是 python 的新手,所以我想知道如果我的 samples 变量已经有我想要的,我如何单独访问这些点,或者创建一个新数组或列表来存储我所有的 x 和 y 值很容易。

编辑:

这是我的 txt 文件的样子:
0.1394 0.8231
1.2149 1.8136
1.3823 0.8263
1.3726 0.8158
1.3694 0.8158
1.3855 0.8123
1.3919 0.8053
1.3694 0.8123
1.3661 0.8123
1.3597 0.7982
1.3565 0.6061
1.3468 0.7126
1.3823 0.7494

有一个很棒的石斑鱼食谱

samples = samples.split() #split on all whitespace [x1,y1,x2,y2,...]
#you may want to map to int with `map(int,samples)`
coordinates = zip(*[iter(samples)]*2) #group by twos [(x1,y1),(x2,y2),...]
x,y = zip(*coordinates) # x= [x1,x2,...] ; y = [y1,y2,...]

这是您可以轻松实现的方法,因为您已经有了 x 和 y 点:

a = [1,2,3]
b = [4,5,6]
print zip(a,b)

输出:[(1, 4), (2, 5), (3, 6)]

如果您只有 x 和 y,只需将它们添加到一个列表中即可:

with open("data1.txt") as f:
    coords = [line.split() for line in f]

print(coords)
[['0.1394', '0.8231'], ['1.2149', '1.8136'], ['1.3823', '0.8263'], ['1.3726', '0.8158'], ['1.3694', '0.8158'], ['1.3855', '0.8123'], ['1.3919', '0.8053'], ['1.3694', '0.8123'], ['1.3661', '0.8123'], ['1.3597', '0.7982'], ['1.3565', '0.6061'], ['1.3468', '0.7126'], ['1.3823', '0.7494']]

要获得浮动,请使用 coords = [list(map(float,line.split())) for line in f]

[[0.1394, 0.8231], [1.2149, 1.8136], [1.3823, 0.8263], [1.3726, 0.8158], [1.3694, 0.8158], [1.3855, 0.8123], [1.3919, 0.8053], [1.3694, 0.8123], [1.3661, 0.8123], [1.3597, 0.7982], [1.3565, 0.6061], [1.3468, 0.7126], [1.3823, 0.7494]]

您不需要创建两个列表然后压缩,只需在从文件中读取时执行即可。