我想将文件中的数字读入二维数组。
文件内容:
- 包含 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/