【问题标题】:Python, Float Recording Text File, Loading Floats and average themPython,浮点记录文本文件,加载浮点数并平均它们
【发布时间】:2019-02-08 14:03:01
【问题描述】:

我有生物漂浮物,想将它们保存在文本文件中,然后加载并平均它们。这浮动:

0.12
0.23
0.30
0.21
..
..
..

这将保存在文本文件中。

浮动的平均值将显示在标签中。

【问题讨论】:

  • 我如何编写这些浮点数并将其加载到文本文件中。最后,我怎样才能使它们平均起来
  • 欢迎来到 Stack Overflow。请Take the Tour,请务必阅读How do I ask a good question?
  • 这些数字是如何产生的?你是一次读一本还是有一份清单?
  • 一次读一篇。

标签: python floating


【解决方案1】:

为了将浮点数保存到文本文件,您需要将它们转换为字符串。我们将浮点数列表转换为字符串列表,然后用空格符号将它们连接起来,这将是分隔符,然后保存文件。 为了读取一个文本文件并使其成为一个新的浮点数列表,我们需要执行相同的操作但相反。

关于标签,不知道你用的是什么GUI框架。

代码:

list_of_floats=[0.12, 0.23, 0.30, 0.21]

def save(path,l):
    with open(path,'w') as file:
        file.write(' '.join(map(str,l)))

def load(path):
        with open(path,'r') as file:
            return list(map(float,file.read().split()))

save('file.txt',list_of_floats)
new_list=load('file.txt')
print(sum(new_list)/len(new_list))

【讨论】:

  • 谢谢igor,我想打印它们的平均值
  • 我已经编辑了代码。平均值是列表的总和除以它的长度
  • 如果浮点数不稳定,我们如何编辑代码?例如:我们有 list_of_floats=[0.12, 0.23, 0.30, 0.21],如果浮点数在一秒钟内出现不规则。例如:0.12 0.13。 ......总是......
  • 我不明白你的意思。你能说得更具体点吗?
【解决方案2】:

这是一个健壮的代码:

import numpy as np
import os
x = np.arange(12).reshape(4, 3)
x=x/23
print("Original array:")
print(x)
header = 'col1 col2 col3'
np.savetxt('temp.txt', x, fmt="%1.3f", header=header)
print("After loading, content of the text file:")
result = np.loadtxt('temp.txt')
print(result)
print('Lets do a calculation on it :')
print(sum(result)/len(result))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多