【问题标题】:Python 3.2: File input/output with loops [closed]Python 3.2:带循环的文件输入/输出[关闭]
【发布时间】:2013-11-03 15:39:53
【问题描述】:

我如何在下面使用循环来做同样的事情来使程序更高效而不是蛮力?

我正在尝试从文件中读取值,将它们转换为浮点数,取前三个数字的平均值,将平均值写入一个新文件,然后继续读取接下来的三个数字。

例子:

原始文件:

20.1
18.2
24.3
16.1
45.5
42.3
46.1
43.8
44.4

新文件:

20.87
19.53
28.63
34.63
44.63
44.07
44.77

这是我的代码:

def smooth(rawDataFilename, smoothDataFilename):
    aFile = open(rawDataFilename, 'r')
    newFile = open(smoothDataFilename, 'w')

    num1 = float(aFile.readline())
    num2 = float(aFile.readline())
    num3 = float(aFile.readline())
    num4 = float(aFile.readline())

    smooth1 = (num1 + num2 + num3) / 3
    smooth2 = (num2 + num3 + num4) / 4

    newFile.write(str(format(smooth1, '.2f')))
    newFile.write('/n')
    newFile.write(str(format(smooth2, '.2f')))

    aFile.close()
    newFile.close()

【问题讨论】:

  • 会发生什么,什么不会?
  • 您是在寻找移动平均线,还是每组 3 个的平均值?你的问题和你的数字说明了两件事。

标签: python file for-loop file-io while-loop


【解决方案1】:

我会用循环解决你的任务:

def smooth(rawDataFilename, smoothDataFilename):
    data = []
    with open(rawDataFilename, 'r') as aFile, open(smoothDataFilename, 'w') as newFile:
        for line in aFile:
            num = float(line)
            data.append(num)
            if len(data) >= 3:
                smooth = sum(data) / len(data)
                newFile.write(format(smooth, '.2f') + '\n')
                del data[0]

您的解决方案的不同之处:

  • with 负责干净地关闭文件,即使出现错误也是如此
  • 我使用列表来收集数据并进行平滑处理
  • 我在数字之间放置了换行符而不是序列/n

我想您想要代码所示的移动平均线,而不是文本建议的 3 元组平均线。

【讨论】:

    【解决方案2】:

    如果您的任务是从该行中取每组三个数字的平均值,那么可以这样做:

    from itertools import izip
    
    with open('somefile.txt') as f:
       nums = map(float, f)
    
    with open('results.txt', 'w') as f:
       for i in izip(*[iter(nums)]*3):
          f.write('{0:.2f}\n'.format(sum(i) / len(i)))
    

    izip 来自 itertools 的 grouper recipie。但是,我怀疑你需要根据你的实际结果做其他事情。我希望这能让你继续前进。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      相关资源
      最近更新 更多