如何解决需要将文本文件中的每 12 个整数除以 12 以模拟一年中的几个月
我正在创建一个程序,将文本文件中的每 12 个整数除以模拟获取一年的平均降雨量,举个例子,如果在单独的行中有 15 个整数,它将取第一个12 并将总数除以 12 以获得该年的平均值,然后它将最后三个分开并使其成为新的一年,我正在考虑制作一个将月份计数器重置为 0 的 else 语句,但我可以使用一些建议。
def main():
rain_per_month = open('RainperMonth.txt','r')
#this is to open the text file with the numbers
months = 0
#start the accumulator to keep track of the total amount of months
rainfall = 0
#this is to keep track of the total amount of rainfall
years = 0
for line in rain_per_month:
#this is a loop that will go line by line and begin to modify the variables
months += 1
#this is increasing the number of months according to the number of lines
#for example if there are 15 lines it will keep count of those 15 lines as seperate months
rainfall = int(line) + rainfall
#this will convert the numbers on the line from being a symbol for 4 to really being the number 4 and
adding it to the total amount of rainfall
if months % 12 == 0:
avg_rain = rainfall / months
#Where I am going to seperate the different months and calculate the total for eac
print(avg_rain)
#where the caculations for the rain will be made
main()
解决方法
只是稍微修改了您的逻辑。 步骤 ->
- 将文件内容加载到列表中。
- 取长度为 12 的列表的子集(参见 for 循环中的步数)
- 计算平均值。
- 这里,enumerate 将自动递增年份。
def main():
with open('RainperMonth.txt','r') as f:
content = f.read().splitlines()
for years,i in enumerate(range(0,len(content),12),start=1):
rain_per_month = content[i:i+12]
# print(rain_per_month)
rainfall = 0
for months,line in enumerate(rain_per_month,start=1):
rainfall = int(line) + rainfall
avg_rain = rainfall / len(rain_per_month)
print(f'avg_rain = {avg_rain} for year = {years}')
main()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。