How do I iterate over specific parts of a text file in Python?

Python's novice is currently looking for some help. I am reading from a text file with 365 lines of integers. Each integer represents a day of the year. Like this, but for 365 lines:

1102
9236
10643
2376
6815
10394
3055
3750
4181
5452
10745

I need to go through the whole file and divide 365 days into each of 12 months and take the average of each month. For example, the first 31 lines are January, take the average value, print it, and then continue from there ...

At this point, I wrote code that goes through the entire file and gives the total for the year and the average per day, but I was stuck on dividing the file into individual months and taking into account individual averages. What am I doing to achieve this?

Here is my current code:

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 about", round(avg), "steps each day!")

  stepsFile.close()

stepCounter()

I hope this question was clear enough. Thanks for any help!

+4
2

. , 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]

, . , 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
+1

:

month_len = [31, 28, 31,
             30, 31, 30,
             31, 31, 30,
             31, 30, 31]

, , , :

for month_num in range(12):
    # Start a new month

    for day_num in range(month_len[month_num]):
        #Process one day

, Python 0, _ 0-11, day_num - 0-30.

?


, : . :

for month_num in range(1, 12):
    month_len = 31
    if month_num = 2:
        month_len = 28
    elif month_num = 4 or
         month_num = 6 or
         month_num = 9 or
         month_num = 11:
        month_len = 30

    for day_num in range(month_len):
0

Source: https://habr.com/ru/post/1688243/


All Articles