0 python file-io json dump list
我已经收到由python中的json转储生成的文本文件,如下所示:
[0.1,0.1,0.2,0.3]
[0.1,0.3,0.4,0.3]
[0.1,0.1,0.3,0.3]
[0.3,0.1,0.5,0.3]
.
.
.
[0.1,0.1,0.3,0.3]
[0.3,0.4,0.6,0.3]
Run Code Online (Sandbox Code Playgroud)
等等〜相当多的线〜> 10,000,000
我想找出最快/最有效的方法来读取文件,并将它们实际转换为列表。
我有一个程序,该程序具有for循环,该循环运行带有列表的特定操作:
for x in range(filelength):
for y in list(each line from the file):
use the numbers from each list to perform certain operations
Run Code Online (Sandbox Code Playgroud)
我当时正在考虑从文本文件中解析出所有括号,并将每个值逗号分隔为每一行的空白列表(这可能很慢且很耗时),但是我认为可能存在python的功能来转换以字符串形式表示的list可以轻松快速地放入python中的实际列表中。
任何想法或建议,将不胜感激。
用于ast.literal_eval()将每一行解析回Python列表:
import ast
with open(filename, 'r') as fh:
for line in fh:
listobj = ast.literal_eval(line)
Run Code Online (Sandbox Code Playgroud)
ast.literal_eval()接受一个字符串并将其解释为Python文字值;直接支持列表和浮点值:
>>> ast.literal_eval('[0.1,0.1,0.2,0.3]\n')
[0.1, 0.1, 0.2, 0.3]
Run Code Online (Sandbox Code Playgroud)