0

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

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

例子:

原始文件:

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

2 回答 2

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 元组平均值。

于 2013-11-03T16:08:52.830 回答
0

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

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的石斑鱼食谱。但是,我怀疑你需要根据你的实际结果做其他事情。我希望这能让你继续前进。

于 2013-11-03T16:11:02.093 回答