如何将文本文件读取为浮动列表?

How to read text file as list of floats?

这似乎是一个简单的问题,但在 Stack 社区找不到它。我在文本文件中有一个类似于下面的数据集。我想将它作为一个列表来读取,每个值都是一个浮点数。目前,所需的简单列表(也在下面)的输出非常奇怪。

data.txt:

[1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814,..]

尝试的代码:

my_file = open(r"data.txt", "r")
content = my_file.read()
content_list = content.split(",")
my_file.close()

输出是奇数。值是字符串和列表内部的列表和添加的空格:

当前结果:

['[1130.1271455966723',
 ' 1363.3947962724474',
 ' 784.433380329118',
 ' 847.2140341725295',
 ' 803.0276763894814',
 ' 913.7751118925291',
 ' 1055.3775618432019',...]']

我也用下面的代码尝试了这里的方法(How to convert string representation of list to a list?)但是产生了一个错误:

import ast
x = ast.literal_eval(result)
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: ['[1130.1271455966723', '1363.3947962724474', ' 784.433380329118', ' 847.2140341725295', ' 803.0276763894814',...]']

理想结果:

list = [1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814]

您的数据有效 JSON,因此只需使用相应的模块即可为您处理所有解析:

import json

with open("data.txt") as f:
    data = json.load(f)

print(data)

输出:

[1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814]