对我来说,这种看似简单的问题就是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:]]
在此处查找生成器表达式。它们确实可以将您的代码简化为离散的功能单元!想象一下在C ++中用4行代码做同样的事情……那将是一个怪物。特别是列表生成器,当我还是C ++时,我一直希望自己拥有类似的东西,而且我常常最终会构建自定义函数来构造所需的每种数组。