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

前端之家收集整理的这篇文章主要介绍了python – 从文本文件中读取多个数字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 python编程的新手,需要帮助才能做到这一点.

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

  1. 12 35 21
  2. 123 12 15
  3. 12 18 89

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

解决方法

在python中,您从文件中读取一行作为字符串.然后,您可以使用字符串获取所需的数据:
  1. with open("datafile") as f:
  2. for line in f: #Line is a string
  3. #split the string on whitespace,return a list of numbers
  4. # (as strings)
  5. numbers_str = line.split()
  6. #convert numbers to floats
  7. numbers_float = [float(x) for x in numbers_str] #map(float,numbers_str) works too

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

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

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

  1. def function(x,y,z):
  2. return x+y+z

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

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

猜你在找的Python相关文章