如何在Python中循环遍历文本文件的某些部分?

2024-09-30 02:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,一个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()

我希望这个问题足够清楚。谢谢你的帮助!你知道吗


Tags: 文件代码countline代表整数stepsavg
2条回答

首先,您需要一个每月天数的列表:

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开始,所以month_num最多只能运行0-11,day_num最多只能运行0-30。你知道吗

你能从那里拿走吗?你知道吗


对OP评论的回应

好吧,你是残疾人:名单是不允许的。相反,请尝试以下方法:

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):

你必须知道每个月的天数。可以使用固定表,也可以询问^{}模块:

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]

如果你决定使用一个固定的表,唯一感兴趣的月份是闰年的二月。如果^{}为真,就可以增加这个值。你知道吗

给定一个每行整数的打开文件,您只需适当地slice它,将int()映射到片上,然后使用^{}

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

相关问题 更多 >

    热门问题