Python – 打印给定年份列表中的闰年数量
在学校或大学中,处理闰年可能会很棘手。当我们想要确定给定的年份是否为闰年时,简单的方法是将其除以四。当闰年能被4和100整除时,它是闰年;否则,它不是闰年。当用户给出一个从10到100范围的年份列表时,这是一个繁琐的过程并且耗费很多时间。在这种情况下,Python使用简单的代码来解决问题。
要打印出列表中的闰年数量,我们需要了解闰年是什么意思。它是每隔四年出现一次的一个时间断,拥有366天,其他年份只有365天。闰年的额外一天被添加到2月份。
方法
方法1 – 使用lambda函数
方法2 – 使用calendar模块
方法3 – 使用条件语句
方法1:使用lambda函数打印出列表中的闰年数量的Python程序
通过导入calendar模块以及lambda函数来获取列表长度的方法。
算法
- 步骤1 - 导入calendar模块以使用名为isleap()的函数。
-
步骤2 - 初始化列表,其中包含年份。
-
步骤3 - 在定义lambda函数时,总是使用filter函数。
-
步骤4 - 打印列表中的闰年以及闰年的数量。
示例
#importing the library
import calendar
#initializing the list with integer elements
list1 = [1998, 1987, 1996, 1972, 2003]
#iterating through the list using for loop
#using the isleap(), filter() function is used to find the leap year
leaplist = list(filter(lambda num: calendar.isleap(num), list1))
#returns the final length
print("Leap years from the list are: " , leaplist)
print("Total number of leap years: ", len(leaplist))
输出
Leap year from the list are: [1996, 1972]
Total number of leap year: 2
方法二:使用条件语句的 Python 程序打印年份列表中的闰年数量
初始化元素列表,并利用条件语句满足要求,找出哪些是闰年。
算法
- 步骤 1 :将年份列表赋值给变量“list1”,并定义一个空列表。
-
步骤 2 :通过迭代,当年份在列表中时,它应满足年份除以 4 等于该年份除以 100 的结果。
-
步骤 3 :或者通过简单运算,当年份除以 400 时,应能整除。
-
步骤 4 :该过程会一直进行,直到检查完列表中的所有元素。
-
步骤 5 :然后返回闰年的总数。
示例
#initializes the list with years as input
list1 = [1998, 1987, 1996, 1972, 2003]
#initializing the empty list
leaplist = []
#for loop is used to iterate through the list
#condition is used to print the result
for num in list1:
if ((num%4==0 and num%100!=0) or (num%400==0)):
print("Leap year from the list is: ",num)
leaplist.append(num)
#finally printing the number of leap years in the given list
print("Total number of leap years: ", len(leaplist))
输出
Leap year from the list is: 1996
Leap year from the list is: 1972
Total number of leap year: 2
第三种方法:使用Calendar模块打印年份列表中闰年的数量的Python程序
使用calendar模块从元素列表中识别闰年。由于使用了该库,因此未使用条件语句。
算法
- 步骤1: 导入所需的calendar模块以处理闰年。
-
步骤2: 使用一定数量的年份初始化列表,并将列表中的闰年存储在leaplist变量中。
-
步骤3: 使用for循环遍历列表元素,并借助isleap()函数直接找到闰年。
-
步骤4: 满足条件时打印闰年的总数。
示例
#importing the library
import calendar
#initializing the list with integer elements
list1 = [1998, 1987, 1996, 1972, 2003]
#initializing the empty list
leaplist = []
#iterating through the list using for loop
#using the isleap() function to find the leap year
for num in list1:
leap = calendar.isleap(num)
if leap:
print("Leap year from the list is: ",num)
leaplist.append(num)
#returns the final length
print("Total number of leap years: ", len(leaplist))
输出
Leap year from the list is: 1996
Leap year from the list is: 1972
Total number of leap year: 2
结论
列表数据结构处理不同数据类型的元素,如整数、浮点数或字符串。元素需要在方括号内用逗号分隔来定义。可以使用诸如日历、DateTime和条件语句的模块提供的方法。