首页 > 解决方案 > 列出年份列表中闰年数量的功能

问题描述

我不是在寻找答案,而是在寻找正确方向的指针来自己解决这个问题。

我有一个问题,我有一个函数可以返回八年列表中的闰年数。我不确定如何处理这个问题。我尝试过使用 FOR LOOP,也尝试过同时使用 calendar.isleap 和 calendar.leapdays 方法,但我似乎遗漏了一些东西,因为我仍然遇到错误。

--- 代码如下 ---

def countLeapYears(yearList):

(学生代码在这里。)

print(countLeapYears([2001, 2018, 2020, 2090, 2233, 2176, 2200, 2982]))
print(countLeapYears([2001, 2018, 2020, 2092, 2204, 2176, 2200, 2982]))

我已经编辑并提出了这个问题,因为我的请求因看起来信息不足而被标记为暂停。所以上面是实际的问题。

我尝试的是这样的:

ly = 0
for i in yearList:
    if i % 4 == 0:
        ly += 1

谢谢。

标签: pythonlistleap-year

解决方案


好的...感谢我得到的一些输入。在一些帮助下将我推向正确的方向,这就是我所拥有的。它有效,答案是我应该做的。

import calendar

def countLeapYears(yearList):

    j=0
    for i in listYears:
        if calendar.isleap(int(i)):
            j += 1
    return j

预期输出:2

打印(countLeapYears([2001, 2018, 2020, 2090, 2233, 2176, 2200, 2982]))

预期输出:4

打印(countLeapYears([2001, 2018, 2020, 2092, 2204, 2176, 2200, 2982]))


推荐阅读