Python 为什么我的程序';结果没有';每30天和闰年的平均计数似乎不正确?

Python 为什么我的程序';结果没有';每30天和闰年的平均计数似乎不正确?,python,Python,这是我在指定闰年条件下的代码: import random f = open('yearlystep.txt','w') #write random steps for one year for y in range(366): x = random.randint(0,1000) f.write(str(x)+'\n') f.close() f = open('yearlystep.txt','r') total = 0 count = 0 for x in

这是我在指定闰年条件下的代码:

import random
f = open('yearlystep.txt','w')          #write random steps for one year
for y in range(366):
    x = random.randint(0,1000)
    f.write(str(x)+'\n')
f.close()

f = open('yearlystep.txt','r')
total = 0
count = 0
for x in range(12):
    count+=1
    if count % 2 == 0 and count!=2:
        num = 30
    elif count == 2:
        num = 28
    else:
        num = 31
    for y in range(num):
        r = f.readline()
        total += int(r)
    avg = total/num
    total = 0
    
    print(avg)

f.close()
这是我一年中每30天计数的代码:

for x in range(12):
   for y in range(30):
        r = f.readline()
        total += int(r)
   avg = total/30
   total = 0
    
   print(avg)

f.close()
意外输出(向上为每30天一次,向下为闰年,2月为28天):


我试着将它们与30天内的相同月份进行比较,我认为它们应该得到相同的结果,因为我为每个数字指定了条件,没有提醒,这是偶数除以30,如代码图1所示。我不明白为什么它们看起来完全不同,因为有些应该是一样的。我的逻辑或代码是否有问题?谁能给我解释一下吗?谢谢。

我不希望任何平均值都是一样的。想想前几个月,想想哪些行将被读取和求和以产生每个平均值

Leap Year Version 
Jan:   0-30   (first 31)      
Feb:   31-59  (next 29)       
Mar:   60-90  (next 31)       
Apr:   91-120 (next 30)       

Naive Version
Jan:   0-29   (first 30)
Feb:   30-59  (next 30)
Mar:   60-89  (next 30)
Apr:   90-119 (next 30)
正如您所看到的,每个月读取的行在任何月份都不相同,因此您很可能会得到不同的平均值(除非由于某种巧合,生成的随机数会导致相等的平均值)

我还没有完成所有的月份,但希望你能看到,随着月份的继续,读取的行将继续不同步

注意:8月(第8个月)有31天,因此这是您需要在算法中解决的问题