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

标签 python file python-3.x

我想将文件中的数字读入二维数组。

文件内容:

  • 包含 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]

关于python - 如何在 Python 中从文件中读取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6583573/

相关文章:

python - Django ;使 View 变薄的技巧

java - 是否可以在 Java 中将文件编码为 Data URI?

python - 仅替换 DataFrame 中最后一次出现的列值

python - 将列添加到稀疏矩阵

python - 在事务中强制提交嵌套的 save()

python - 正则表达式匹配大括号内的数字

linux - 如何在 Linux 上的 SDCARD 中写入超过 2000,000 个文件

python - 使用 Python v3.x 和 C API 解释 Python v2.5 代码(关于整数除法)

Python属性错误: 'module' object has no attribute 'Goslate'

python - 动态插入/更新/选择 mysql python