【问题标题】:How to read a list in a text file in python如何在python中读取文本文件中的列表
【发布时间】:2022-06-30 21:43:09
【问题描述】:

我有这份清单

l1=[[[0,1,2,3,4],[5,6,7]],[8,9,10],[11,12,13,14]]

我将此列表保存在文本文件中

with open('l1.txt', 'w') as f1:
      f1.write(str(l1))

现在我有一个包含列表的文本文件。 如何在 python 中阅读此列表? 我试过了

list1= open("l1.txt", "r")
list2= list1.read()
l1= list2.strip('][').split(', ')

有了这个

l1=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14']

但这不是我一开始的清单

【问题讨论】:

  • l1=[[[0,1,2,3,4][5,6,7]][8,9,10][11,12,13,14]]TypeError: list indices must be integers or slices, not tuple 的 python 不正确,请修正

标签: python list text


【解决方案1】:

您需要使用eval()函数从文本文件中显式读取,然后转换为有效的Python多维列表:

l1 = eval("[[[0,1,2,3,4],[5,6,7]],[8,9,10],[11,12,13,14]]")
print(l1)

输出:*

[[[0, 1, 2, 3, 4], [5, 6, 7]], [8, 9, 10], [11, 12, 13, 14]]

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2023-01-19
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多