我有一个如下文字文件。我想将给定值读作浮点列表。之后我会做一些计算。我使用split函数和convertion来浮动。但我无法转换第一个和最后一个,因为这两个方括号。 ([])。它给出了如下错误。
文件格式
[-1.504, 1.521, 1.531, 1.1579, -2.2976, 2.5927,... 1000 records]
[2.758, -0.951, -1.7952, 0.4255, 2.5403, 1.0233,... 1000 records]
[0.682, -2.205, 2.1981, 2.1329, 0.1574, -0.4695,... 1000 records]
错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: [0.682
我使用的代码
F = open('XYZ.txt', 'r')
>>> for line in F:
... P = line.split(',')
... P
任何人都可以告诉我如何将这些值读入浮点数组中,如下所示。
X = [-1.504, 1.521, 1.531, 1.1579, -2.2976, 2.5927,... 1000 records]
Y = [2.758, -0.951, -1.7952, 0.4255, 2.5403, 1.0233,... 1000 records]
Z = [0.682, -2.205, 2.1981, 2.1329, 0.1574, -0.4695,... 1000 records]
然后我可以调用X [1],X [999]
等值答案 0 :(得分:7)
使用ast.literal_eval()
将每一行解析为浮点数列表:
import ast
with open('XYZ.txt', 'r') as infh:
for line in infh:
row = ast.literal_eval(line)
print row
ast.literal_eval()
将每一行解释为包含文字Python值,支持列表,元组,字典,字符串和数字文字。
演示:
>>> import ast
>>> ast.literal_eval('[-1.504, 1.521, 1.531, 1.1579, -2.2976, 2.5927]\n')
[-1.504, 1.521, 1.531, 1.1579, -2.2976, 2.5927]
答案 1 :(得分:2)
你可以评估它们:
for line in F:
my_arr = eval(line)
答案 2 :(得分:2)
使用json.loads():
import json
line = "[-1.504, 1.521, 1.531, 1.1579, -2.2976]"
row = json.loads(line)
编辑:我发现@Martijn回答很有趣,因为我几乎从不使用ast,所以我运行了一个小基准:
import timeit
import random
line = [random.random() for x in range(1000)]
n = 10000
json_setup = 'line = "{}"; import json'.format(line)
json_work = 'json.loads(line)'
json_time = timeit.timeit(json_work, json_setup, number=n)
print "json: ", json_time
ast_setup = 'line = "{}"; import ast'.format(line)
ast_work = 'ast.literal_eval(line)'
ast_time = timeit.timeit(ast_work, ast_setup, number=n)
print "ast: ", ast_time
print "time ratio ast/json: ", ast_time / json_time
我多次运行此代码并始终得到这样的结果:
$ python json-ast-bench.py
json: 4.3199338913
ast: 28.4827561378
time ratio ast/json: 6.59333148483
因此,对于这个用例,似乎ast几乎要慢一个数量级。
修改: Why is json.loads an order of magnitude faster than ast.literal_eval?