我该如何使用循环来提高程序的效率而不是暴力?在
我试图从一个文件中读取值,将它们转换成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()
如果您的任务是从该行中取每组三个数字的平均值,则可以使用以下方法:
^{来自itertools的grouper recipie。不过,根据你的实际结果,我怀疑你还需要别的东西。我希望这能让你振作起来。在
我会用一个循环来解决你的任务:
与解决方案的差异:
with
即使出错,也要小心地关闭文件/n
我想你想要的是代码所示的移动平均值,而不是文本中建议的三元组平均值。在
相关问题 更多 >
编程相关推荐