最初,我只是简单地使用 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 新手,所以我想知道如果我的样本变量已经具有我想要的内容,我如何单独访问这些点,或者创建一个新的数组或列表来轻松存储我的所有 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
最佳答案
如果您只有 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']]
要获取 float ,请使用 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]]
您不需要创建两个列表然后进行压缩,只需在读取文件时执行即可。
关于python - 在Python中读取文件后尝试创建x和y值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388250/