【问题标题】:How to import a list of lists (of integers) from text file and treat them mathematically?如何从文本文件中导入列表(整数)列表并以数学方式处理它们?
【发布时间】:2019-02-24 04:33:30
【问题描述】:

我在 text.txt 文件中有数据

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[10, 11, 12], [13, 14, 15], [16, 17, 18]]

等等 我想读取文本文件的每一行并将它们视为整数,例如在 3d 空间中绘制这些点。当我通过

导入文件时
with open('text.txt') as f:
    content = f.readlines()
    for x in content:
        print(x)

它是:

'[','[','1' etc...

所以我很困惑使用什么作为 split() 函数的分隔符。将不胜感激一些建议。 提前致谢。

【问题讨论】:

    标签: python string split python-import readlines


    【解决方案1】:

    您可以使用内置函数eval() 来解释文件中的python 列表:

    with open('file.txt') as fp:
        for line in fp:
            pylist = eval(line)
            print(pylist)
    

    如果您不能 100% 确定此文件的性质,或者它是否包含其他用户手动生成的数据,正如@G_M 所指出的,您应该使用只会评估 python 文字的ast.literal_eval:

    import ast
    
    with open('file.txt') as fp:
        for line in fp:
            pylist = ast.literal_eval(line)
            print(pylist)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多