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)
# 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:]]
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]
不确定为什么需要w,h。如果这些值实际上是必需的,并且意味着只应读取指定数量的行和列,则可以尝试以下操作:
对我来说,这类看似简单的问题就是Python的全部内容。尤其是如果你来自C++之类的语言,简单的文本解析可能会让你感到痛苦,你会很欣赏Python能给你的功能性单元解决方案。我会用几个内置函数和一些生成器表达式来简化它。
你需要
open(name, mode)
,myfile.readlines()
,mystring.split()
,int(myval)
,然后你可能想用两个生成器把它们组合在一起。查找生成器表达式here。他们真的可以把你的代码简化成离散的功能单元!想象在C++中用4行做同样的事情…会是个怪物。尤其是列表生成器,当我是C++的时候,我总是希望我有这样的东西,我经常会结束自定义函数来构造我想要的每一种数组。
假设您没有多余的空白:
您可以将最后一个for循环压缩为嵌套列表理解:
相关问题 更多 >
编程相关推荐