目前,一个Python初学者正在寻找一些帮助。我在读一个有365行整数的文本文件。每个整数代表一年中的一天。像这样,但对于365行:
1102
9236
10643
2376
6815
10394
3055
3750
4181
5452
10745
我需要浏览整个文件,将365天分为12个月,取每个月的平均数。例如,前31行是一月,取平均值,打印出来,然后从那里继续。。。你知道吗
在这一点上,我已经编写了贯穿整个文件的代码,并给出了一年的总数和每天的平均值,但我仍然坚持将文件分为单独的几个月,并取每个月的平均值。我该怎么做才能做到这一点?你知道吗
这是我目前的代码:
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()
我希望这个问题足够清楚。谢谢你的帮助!你知道吗
首先,您需要一个每月天数的列表:
现在写一个循环来逐步遍历月份,另一个循环在内部遍历天数:
请记住,Python索引从0开始,所以month_num最多只能运行0-11,day_num最多只能运行0-30。你知道吗
你能从那里拿走吗?你知道吗
对OP评论的回应
好吧,你是残疾人:名单是不允许的。相反,请尝试以下方法:
你必须知道每个月的天数。可以使用固定表,也可以询问^{} 模块:
如果你决定使用一个固定的表,唯一感兴趣的月份是闰年的二月。如果^{} 为真,就可以增加这个值。你知道吗
给定一个每行整数的打开文件,您只需适当地slice它,将} :
int()
映射到片上,然后使用^{其中
the_file
只是相关问题 更多 >
编程相关推荐