Skip to main content
 首页 » 编程设计

python之使用 Python 范围和日历检查闰年

2025年05月04日14jiqing9006

菜鸟问题。是否有更理想的方式来使用范围和日历来表达范围。如果我范围内的任何年份是闰年,则希望设置打印 True

year =  calendar.isleap(range(2016,2036)) 
 
 
 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/usr/lib/python2.7/calendar.py", line 99, in isleap 
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) 
TypeError: unsupported operand type(s) for %: 'list' and 'int' 

请您参考如下方法:

听起来您想使用 Python any内置;

In [1]: import calendar 
 
In [2]: test1 = any(calendar.isleap(y) for y in range(2016, 2036)) 
 
In [3]: test2 = any(calendar.isleap(y) for y in range(2097, 2103)) 
 
In [4]: print(test1) 
True 
 
In [5]: print(test2) 
False