[英]Python - How to read lines of lists in a text file directly into lists in python
我已經收到由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]
等等〜相當多的線〜> 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
我正在考慮從文本文件中解析出所有括號,並將每個值逗號分隔為每行的空白列表(這可能會很慢並且很耗時),但是我認為可能存在python的功能來轉換以字符串形式表示的list可以輕松快速地放入python中的實際列表中。
任何想法或建議,將不勝感激。
使用ast.literal_eval()
將每一行解析回Python列表:
import ast
with open(filename, 'r') as fh:
for line in fh:
listobj = ast.literal_eval(line)
ast.literal_eval()
接受一個字符串並將其解釋為Python文字值; 直接支持列表和浮點值:
>>> ast.literal_eval('[0.1,0.1,0.2,0.3]\n')
[0.1, 0.1, 0.2, 0.3]
您說這是“由json轉儲生成的”,並且每一行看起來都像有效的JSON,因此正確的做法是將每一行解析為JSON:
import json
with open(filename) as f:
the_lists = map(json.loads, f)
由於您只想直接遍歷列表,因此在循環中進行loads
可能會更簡單:
import json
with open(filename) as f:
for line in f:
for column in json.loads(line):
# your code here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.