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

Given output is : [['2', '1', '3'], ['3', '1', '3'], ['2', '9']]
Wanted output is : [[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 
评论
  • 不No
    不No 回复

    修改这行

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

    You should also be aware that python comes with csv.reader that can already read comma delimited text files. So does numpy if you want to read into a 2D array for linear algebra purposes.