如何在Python中从文件中读取数字?

我想将文件中的数字读入二维数组。


文件内容:


包含w,h的行

h行包含w个以空格分隔的整数

例如:


4 3

1 2 3 4

2 3 4 5

6 7 8 9


哈士奇WWW
浏览 2905回答 3
3回答

慕后森

假设您没有多余的空格: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]

慕田峪9158850

对我来说,这种看似简单的问题就是Python的全部意义所在。尤其是如果您来自像C ++这样的语言,其中简单的文本解析可能会给您带来麻烦,那么您将非常感激python可以为您提供的功能单位明智的解决方案。我将通过几个内置函数和一些生成器表达式使它保持非常简单。你需要open(name, mode),myfile.readlines(),mystring.split(),int(myval),然后你可能会想使用几个发电机来把它们放在一起的Python的方式。# This opens a handle to your file, in 'r' read modefile_handle = open('mynumbers.txt', 'r')# Read in all the lines of your file into a list of lineslines_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 matrixmy_data = [[int(val) for val in line.split()] for line in lines_list[1:]]在此处查找生成器表达式。它们确实可以将您的代码简化为离散的功能单元!想象一下在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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python