【问题标题】:Create nested list from file columns (Python)从文件列创建嵌套列表(Python)
【发布时间】:2018-04-15 23:27:03
【问题描述】:

我正在尝试使用 .txt 文件的行创建一个嵌套列表,但无法达到我想要的形式。

.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]]

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    您需要将表示列表的字符串转换为实际列表。你可以使用ast.literal_eval 喜欢:

    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)
    

    或使用list comprehension 之类的:

    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]]
    

    【讨论】:

      【解决方案2】:

      我正在考虑类似的事情并想出了以下使用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)
      

      【讨论】:

      • 或者斯蒂芬-劳赫所说的:)
      • 您的代码与@stephen-rauch 的代码没有太大区别。请注意,您可以在 ast.literal_eval(element) 中省略 ast
      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2017-06-14
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多