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

2024-04-26 00:13:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

文件内容:

  • 包含w,h的线
  • 用空格分隔的包含w个整数的h行

例如:

4 3
1 2 3 4
2 3 4 5
6 7 8 9

Tags: 文件内容数字整数数组空格
3条回答

不确定为什么需要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)

对我来说,这类看似简单的问题就是Python的全部内容。尤其是如果你来自C++之类的语言,简单的文本解析可能会让你感到痛苦,你会很欣赏Python能给你的功能性单元解决方案。我会用几个内置函数和一些生成器表达式来简化它。

你需要open(name, mode)myfile.readlines()mystring.split()int(myval),然后你可能想用两个生成器把它们组合在一起。

# 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:]]

查找生成器表达式here。他们真的可以把你的代码简化成离散的功能单元!想象在C++中用4行做同样的事情…会是个怪物。尤其是列表生成器,当我是C++的时候,我总是希望我有这样的东西,我经常会结束自定义函数来构造我想要的每一种数组。

假设您没有多余的空白:

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]

相关问题 更多 >