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

方法 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

方法 3:使用 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

結論

列表資料結構處理不同資料型別的元素,例如整數、浮點數或字串。元素需要在方括號內定義,並用逗號分隔。方法給出了使用 calendar、DateTime 等模組以及使用條件語句的方法。

更新於: 2023-08-29

196 次檢視

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告

© . All rights reserved.