我有一个.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
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]]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句