[读取文件并将其转换为嵌套列表时的Python问题,

问题描述 投票:0回答:1

我想阅读每行中用逗号分隔的数字的文本文件列表,例如:

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

并且想要将其转换为列表列表。我当前的功能如下:

def nested_int_list_from_file(file):
    f = open(file)
    xs = []
    for line in f :
        if not line.strip():
            continue
        else:
            x = line.strip().split(', ')
            line = [(i) for i in x]
            xs.append(line)
    return xs

当前,输出中的数字是字符串:

[['2', '1', '3'], ['3', '1', '3'], ['2', '9']]

但是我希望它们改为数字:

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

我该如何更改我的功能?

python
1个回答
2
投票

修改此行

line = [int(i) for i in x]

[您还应该知道python随附csv.reader,它已经可以读取以逗号分隔的文本文件。如果要出于线性代数目的而读入2D数组,numpy也是如此。


0
投票

使用numpy功能将str转换为int

© www.soinside.com 2019 - 2024. All rights reserved.