我有一个包含'lists'的.txt文件
3
[2,4,6,7]
[9,11,10,12,13]
当我做num_list = open("file.txt").read().splitlines()
时
然后打印出来,结果是
['3','[2,4,6,7]','[9,11,10,12,13]']
如何更改它以使我的结果
[3, [2,4,6,7], [9,11,10,12,13]]
编辑: 我试过这个,而且很接近
for i in num_list:
for j in i:
j.split(" ")
list(j)
print(j)
但现在输出
['2', '135', '2467']
答案 0 :(得分:2)
可以使用literal_eval
:
import ast
with open('file.txt') as f:
lists = [ast.literal_eval(line) for line in f]
print(lists)
打印
[3, [2, 4, 6, 7], [9, 11, 10, 12, 13]]