目前,
Python初学者正在寻求一些帮助.我正在阅读一个包含365行整数的文本文件.每个整数代表一年中的某一天.像这样,但365行:
1102
9236
10643
2376
6815
10394
3055
3750
4181
5452
10745
我需要浏览整个文件,将365天分为12个月中的每一天,并取每个月的平均值.例如,前31行是1月,取平均值,打印出来,然后从那里继续……
在这一点上,我已经编写了贯穿整个文件的代码,并给出了一年中的总数和每天的平均值,但我仍然坚持将文件拆分为单独的月份并采用单独的平均值.我该怎么做才能做到这一点?
这是我目前的代码:
import math
def stepCounter ():
stepsFile = open("steps.txt", "r")
stepsFile.readline()
count = 0
for line in stepsFile:
steps = int(line)
count = count + steps
avg = count / 365
print(count, "steps taken this year!")
print("That's about", round(avg), "steps each day!")
stepsFile.close()
stepCounter()
我希望这个问题足够清楚.谢谢你的帮助!
最佳答案 你必须拥有每月的天数.要么使用固定的表,要么可以询问
calendar
模块:
In [11]: months = [calendar.monthrange(2017, m)[1] for m in range(1, 13)]
In [12]: months
Out[12]: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
如果您决定使用固定表格,那么在闰年期间,唯一的利息月份是2月份.如果calendar.isleap()
为True,你可以增加它.
给定一个每行的整数打开文件,你可以简单地将它放在slice上,将int()映射到切片上,然后使用statistics.mean()
:
In [17]: from statistics import mean
In [18]: from itertools import islice
In [19]: [mean(map(int, islice(the_file, mdays))) for mdays in months]
Out[19]: [15, 44.5, 74, 104.5, 135, 165.5, 196, 227, 257.5, 288, 318.5, 349]
其中the_file很简单
In [13]: from io import StringIO
In [14]: the_file = StringIO()
In [15]: the_file.writelines(map('{}\n'.format, range(365)))
In [16]: the_file.seek(0)
Out[16]: 0