如何从Python中的文件读取数字? [英] How to read numbers from file in Python?

查看:936
本文介绍了如何从Python中的文件读取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to read numbers from file into two dimensional array.

文件内容:


  • 包含w,h

  • h包含用空格分隔的w整数的行

例如:

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


推荐答案

假设你没有无关的空白:

Assuming you don't have extraneous whitespace:

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()])

您可以将最后一个循环集中到嵌套列表理解中:

You could condense the last for loop into a nested list comprehension:

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中的文件读取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆