使用Python计算两年之间的闰年数和它们的平均值。

问题描述 投票:0回答:1

如何用下面的python脚本计算闰年数并计算其平均值?

start = int(input("Enter start year: "))
end = int(input("Enter end year: "))

if start <= end:
    leap_years = [str(x + start) for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
    leap_years[-1] += "."
    print(f"Here is a list of leap years between {start} and {end}:\n{(', '.join(leap_years))}")

from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)

print(len(leap_years))
print(avg_leap_year)

如果这个脚本可以改进,减少冗余,请告诉我。

谢谢你

python python-3.x spyder
1个回答
1
投票

这里有一个简单的解决方案。

from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)
© www.soinside.com 2019 - 2024. All rights reserved.