您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 从文本文件中读取多个数字

5b51 2022/1/14 8:22:56 python 字数 1951 阅读 553 来源 www.jb51.cc/python

我是 python编程的新手,需要帮助才能做到这一点. 我有一个包含几个数字的文本文件: 12 35 21 123 12 15 12 18 89 我需要能够读取每行的单个数字,以便能够在数学公式中使用它们. 在python中,您从文件中读取一行作为字符串.然后,您可以使用字符串获取所需的数据: with open("datafile") as f: for line in f: #Lin

概述

我有一个包含几个数字的文本文件

12 35 21
123 12 15
12 18 89

我需要能够读取每行的单个数字,以便能够在数学公式中使用它们.

with open("datafile") as f:
    for line in f:  #Line is a string
        #split the string on whitespace,return a list of numbers 
        # (as strings)
        numbers_str = line.split()
        #convert numbers to floats
        numbers_float = [float(x) for x in numbers_str]  #map(float,numbers_str) works too

我已经完成了所有这一切的步骤,但你会经常看到人们组合它们:

with open('datafile') as f:
    for line in f:
        numbers_float = map(float,line.split())
        #work with numbers_float here

最后,在数学公式中使用它们也很容易.首先,创建一个函数

def function(x,y,z):
    return x+y+z

现在遍历你的文件调用函数

with open('datafile') as f:
    for line in f:
        numbers_float = map(float,line.split())
        print function(numbers_float[0],numbers_float[1],numbers_float[2])
        #shorthand:  print function(*numbers_float)

总结

以上是编程之家为你收集整理的python – 从文本文件中读取多个数字全部内容,希望文章能够帮你解决python – 从文本文件中读取多个数字所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶