我有一个.txt格式的输入数据集,看起来像
[[1, 2, 3], [4, 5, 6]]
[[7, 8, 9], [10, 11, 12]]
如何将其读入3-d python列表,其中第一个索引是行号。例如
list[0][0][0] = 1
list[1][1][2] = 12
答案 0 :(得分:2)
将with open
与循环一起使用以获取每一行,并使用ast.literal_eval
将其添加到列表中,然后将其附加到l_3d
列表中:
import ast
l_3d = []
with open('file.txt', 'r') as f:
for line in f:
l_3d.append(ast.literal_eval(line.rstrip()))
由于@khachik :-),您可以使用json.loads
做同样的事情:
import json
l_3d = []
with open('file.txt', 'r') as f:
for line in f:
l_3d.append(json.loads(line.rstrip()))
现在两种情况下:
print(l_3d)
是:
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
答案 1 :(得分:0)
import numpy as np
import json
with open('test.txt', 'r') as f:
data = f.read()
datalist = data.split('\n')
blank = []
for i in range(len(datalist)):
blank.append(json.loads(datalist[i]))
blank[1][1][1]