为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哈士奇WWW 2019-11-30 13:44:09
我想将文件中的数字读入二维数组。文件内容:包含w,h的行h行包含w个以空格分隔的整数例如:4 31 2 3 42 3 4 56 7 8 9
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

假设您没有多余的空格:


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]


查看完整回答
反对 回复 2019-11-30
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

对我来说,这种看似简单的问题就是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 ++时,我一直希望自己拥有类似的东西,而且我常常最终会构建自定义函数来构造所需的每种数组。


查看完整回答
反对 回复 2019-11-30
?
桃花长相依

TA贡献1860条经验 获得超8个赞

不知道为什么需要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)


查看完整回答
反对 回复 2019-11-30
  • 3 回答
  • 0 关注
  • 2904 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号