如何在 Python 中从文件中读取数字? [英] How to read numbers from file in Python?
本文介绍了如何在 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()])
您可以将最后一个 for 循环压缩为嵌套列表推导式:
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屋!
查看全文