【问题标题】:Python making a nested list from file text [closed]Python从文件文本制作嵌套列表[关闭]
【发布时间】:2020-04-28 12:02:58
【问题描述】:

该文件包含以下文本

2,3,2
2,2,2
2,9

我需要创建一个嵌套列表,以便它返回 [[2,3,2],[2,2,2],[2,9]] 但是当我尝试将字符串转换为 int 时会出现错误

【问题讨论】:

  • 你能显示一些代码吗?
  • int() 函数只接受数字字符串。尝试使用line.split(',') 拆分每一行(其中line 是从文件中读取的行),然后将每个结果传递给int()
  • 感谢您使用 Stack Overflow。如果您可以编辑您的问题以包含代码以及您遇到的任何错误,我们将能够提供帮助。不然怎么办!?

标签: python python-3.x list file nested-lists


【解决方案1】:

试试这个:

假设你的文件名为 test.txt

res = []
with open('test.txt', 'r') as file:
    for line in file:
        res.append(list(map(int, line.split(','))))

print(res)

输出:-

[[2,3,2],[2,2,2],[2,9]]

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2014-10-09
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多