Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从文本文件(例如:[[1,2],[3,4]])输入python中的2d列表_Python_List_File_Input - Fatal编程技术网

从文本文件(例如:[[1,2],[3,4]])输入python中的2d列表

从文本文件(例如:[[1,2],[3,4]])输入python中的2d列表,python,list,file,input,Python,List,File,Input,我有一个.txt格式的输入数据集 [[1, 2, 3], [4, 5, 6]] [[7, 8, 9], [10, 11, 12]] 如何将其读入3D python列表,其中第一个索引是行号,例如 list[0][0][0] = 1 list[1][1][2] = 12 使用和open以及循环获取每一行,并使用ast.literal\u eval将其放入列表,然后将其追加到l\u 3d列表中: import ast l_3d = [] with open('file.txt', 'r'

我有一个.txt格式的输入数据集

[[1, 2, 3], [4, 5, 6]]


[[7, 8, 9], [10, 11, 12]]
如何将其读入3D python列表,其中第一个索引是行号,例如

list[0][0][0] = 1


list[1][1][2] = 12

使用
和open
以及循环获取每一行,并使用
ast.literal\u eval
将其放入列表,然后将其追加到
l\u 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)
是:


你的.txt文件中的每一行都是由两个列表组成的,每个列表都有三个项目吗?不是,但是这个数字是固定的@Reedinationerit看起来像是
literal\u eval的一个替代品,可以是
json.loads
@Sankarshana很乐意帮忙,:-),是的,我一定会@U9前进
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
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]