Python从文件文本制成嵌套列表[关闭]

问题描述 投票:-3回答:1

该文件包含以下文本

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

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

python python-3.x list file nested-lists
1个回答
-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]]

0
投票

您可以使用列表理解来创建此嵌套列表:

with open("data.txt") as f:
    nested_list = [[int(col) for col in row.split(",")] for row in f]
    print(nested_list)
    # [[2, 3, 2], [2, 2, 2], [2, 9]]

或者,如果更容易理解,则可以使用常规的嵌套循环方法:

with open("data.txt") as f:
    nested_list = []
    for line in f:
        row = []

        for col in line.split(","):
            row.append(int(col))

        nested_list.append(row)

    print(nested_list)
    # [[2, 3, 2], [2, 2, 2], [2, 9]]

0
投票

您可以做

with open('test.txt', 'r') as file:
     txt = f.readlines()
print([list(map(int, i.replace('\n', '').split(','))) for i in txt])

将打印

[[2, 3, 2], [2, 2, 2], [2, 9]]
© www.soinside.com 2019 - 2024. All rights reserved.