您还可以使用比 ast 快得多的正则表达式:
import re
with open("in.txt") as f:
r = re.compile("[-]?\d+\.\d+")
data = [list(map(float, r.findall(line))) for line in f]
一些时间安排:
In [14]: %%timeit
with open("test.txt") as f:
data = [literal_eval(line) for line in f]
....:
100 loops, best of 3: 2.01 ms per loop
In [15]: %%timeit
with open("test.txt") as f:
r = re.compile("[-]\d+\.\d+")
data = [list(map(float, r.findall(line))) for line in f]
....:
1000 loops, best of 3: 403 µs per loop
with open("test.txt") as f:
r = re.compile("[-]?\d+\.\d+")
data = [list(map(float, r.findall(line))) for line in f]
....:
In [38]: with open("test.txt") as f:
data2 = [literal_eval(line) for line in f]
....:
In [39]: data == data2
Out[39]: True
只是剥离和拆分会再次更快:
In [40]: %%timeit
....: with open("test.txt") as f:
....: data = [list(map(float, line.strip("[]\n").split(","))) for line in f]
....:
1000 loops, best of 3: 249 µs per loop