kra*_*mir 45 python file python-3.x
我想将文件中的数字读入二维数组.
文件内容:
例如:
4 3
1 2 3 4
2 3 4 5
6 7 8 9
Run Code Online (Sandbox Code Playgroud)
zee*_*kay 73
假设你没有无关的空白:
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()])
Run Code Online (Sandbox Code Playgroud)
您可以将最后一个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]
Run Code Online (Sandbox Code Playgroud)
mac*_*ing 14
对我来说,这种看似简单的问题就是Python的全部意义所在.特别是如果你来自像C++这样的语言,简单的文本解析可能会让你感到痛苦,你会非常感谢python可以提供的功能单元解决方案.我会用几个内置函数和一些生成器表达式来保持它非常简单.
你需要open(name, mode),myfile.readlines(),mystring.split(),int(myval),然后你可能会想使用几个发电机来把它们放在一起的Python的方式.
# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]
Run Code Online (Sandbox Code Playgroud)
在这里查找生成器表达式.它们可以真正将代码简化为独立的功能单元!想象一下,用C++中的4行做同样的事情......这将是一个怪物.特别是列表生成器,当我是C++的时候,我总是希望我有类似的东西,而且我经常最终会构建自定义函数来构建我想要的各种数组.
不知道你为什么需要 w,h。如果这些值实际上是必需的,并且意味着应该只读取指定数量的行和列,那么您可以尝试以下操作:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201499 次 |
| 最近记录: |