如何在Python中从文件中读取数字?


问题内容

我想将数字从文件中读取到二维数组中。

文件内容:

  • 包含w,h的行
  • h行包含w个以空格分隔的整数

例如:

4 3
1 2 3 4
2 3 4 5
6 7 8 9

问题答案:

假设您没有多余的空格:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

您可以将最后一个for循环压缩为嵌套列表推导:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]