python3.2:带循环的文件输入/输出

2024-09-21 03:17:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何使用循环来提高程序的效率而不是暴力?在

我试图从一个文件中读取值,将它们转换成float,取前三个数字的平均值,将平均值写入一个新文件,然后继续处理下三个数字。在

示例:

原始文件:

20.1
18.2
24.3
16.1
45.5
42.3
46.1
43.8
44.4

新文件:

^{pr2}$

这是我的代码:

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()

Tags: 文件readline数字openfloatwrite平均值newfile
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)))

^{来自itertools的grouper recipie。不过,根据你的实际结果,我怀疑你还需要别的东西。我希望这能让你振作起来。在

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

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

我想你想要的是代码所示的移动平均值,而不是文本中建议的三元组平均值。在

相关问题 更多 >

    热门问题