我正在尝试使用.txt文件的行创建嵌套列表,但无法达到我想要的格式。
[1,2,3]
[2,3,4]
[3,4,5]
nested_List = []
file = open("example_File.txt",'r')
for i in file:
element = i.rstrip("\n")
nested_List.append(element)
arch.close()
return (esta)
['[1,2,3]', '[2,3,4]', '[3,4,5]']
[[1,2,3],[2,3,4],[3,4,5]]
答案 0 :(得分:3)
您需要将表示列表的字符串转换为实际列表。您可以使用here之类的:
from ast import literal_eval
nested_list = []
with open("file1", 'r') as f:
for i in f:
nested_list.append(literal_eval(i))
print(nested_list)
或使用ast.literal_eval
之类的:
with open("file1", 'r') as f:
nested_list = [literal_eval(line) for line in f]
print(nested_list)
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
答案 1 :(得分:0)
我在想类似的东西,并提出了以下内容,它使用了python的抽象语法树literal_eval函数。
import ast
nested_List = []
with open("example_File.txt", 'r') as infile:
for i in infile:
element = i.rstrip("\n")
nested_List.append(ast.literal_eval(element))
print(nested_List)