在 python 中,您从文件中读取一行作为字符串。然后,您可以使用该字符串来获取您需要的数据:
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)