如何读取TXT文件并使用行作为浮点值?

问题描述 投票:0回答:1
0, 0
0.4859, 2.5468
0.9718, 5.0936
1.4577, 7.6404
1.9436, 10.1872
2.4295, 12.734
2.9154, 15.2808
3.4013, 17.8276

我有一个类似于上述结构的文本文件。我试图将每行中的第一个浮点数作为 x_location 值,将第二个浮点数作为 y_location 值,并将它们放在列表中。我尝试了从 data.split 到 item[0] 读取的一切。但无法找出一种方法来做到这一点。最后我希望它看起来像:

x_location = [0, 0.4859, 0.9718, 1.4577, 1.9436]
y_location = [0, 2.5468, 5.0936, 7.6404, 10.1872]

有什么办法可以实现这个目标吗?

我尝试使用 data.split 但不断获取 str 值,但我无法可靠地将其转换为浮点值。对于 item[0],我找不到将 str 变成 2 个不同项目的方法。

python split txt
1个回答
0
投票

使用Python:

x_location = []
y_location = []
with open('yourtxtfile.txt', 'r') as f:
    lines = f.read().split('\n')
    for line in lines:
        x, y = [float(i) for i in line.split(',')]
        x_location.append(x)
        y_location.append(y)

print(x_location)
print(y_location)
© www.soinside.com 2019 - 2024. All rights reserved.