Python – 檢查降序排序列表


列表是 Python 語言中一種資料結構,可以在這些“[]”括號記憶體儲不同資料型別元素。資料排序的順序可以是升序或降序。在列表中,當前一個元素大於下一個元素時,則遵循降序,反之,當前一個元素小於下一個元素時,則遵循升序。利用三種不同的方法,給出了在 python 中驗證降序排序列表的方法。

方法

方法 1 - 使用迭代方法

方法 2 - 使用 sort()

方法 3 - 使用 reduce() 方法

方法 1:使用迭代檢查降序排序列表的 Python 程式

該函式定義了一個引數,用於遍歷列表。要遍歷列表的元素,我們需要檢視前一個元素是否大於後一個元素。for 迴圈用於遍歷 num_list,然後當條件滿足時,它遵循降序,否則不遵循。num_list 初始化為一個包含元素的列表。

演算法

  • 步驟 1 - 該函式定義了一個引數 val。

  • 步驟 2 - for 迴圈用於遍歷列表元素的範圍。

  • 步驟 3 - 為了找到降序,值“a”應該小於下一個元素。

  • 步驟 4 - num_list 初始化為一個以某種順序排列的元素列表。

  • 步驟 5 - 基於條件,它檢查給定列表是否為降序。

示例

#is_descending function is defined with one argument as val
def is_descending(val):
   # iterate through the list to check whether every element in the list is greater than the succeeding element
   for a in range(1, len(val)):
      if val[a] > val[a-1]:
         return False
      return True
#initializing the list with elements to check the order of the elements
num_list = [45, 32, 12,98, 100]
#using if else loop the resultant statement is printed
if is_descending(num_list):
   print("Given list follows descending order.")
else:
   print("Descending order is not followed.")

輸出

Descending order is not followed.

方法 2:使用 sort() 方法檢查降序排序列表的 Python 程式

該函式定義了一個引數,用於遍歷列表。要遍歷列表的元素,我們需要檢視前一個元素是否大於後一個元素。sorted() 函式用於檢查它是否按降序排列。num_list 初始化為一個包含元素的列表。然後當條件滿足時,它遵循降序,否則不遵循。

  • 步驟 1 - 建立名為 is_descending() 的函式。

  • 步驟 2 - 為了識別降序,使用 sort() 檢查當前元素是否小於下一個元素。

  • 步驟 3 - 使用元素初始化列表以檢查元素的順序

  • 步驟 4 - 基於條件,它檢查給定列表是否為降序。

示例

#is_descending function is defined with one argument as val
def is_descending(val):
   return val == sorted(val, reverse=True)
num_list = [98, 45, 32, 12]
#using if else loop the resultant statement is printed
if is_descending(num_list):
   print("Given list follows descending order.")
else:
   print("Descending order is not followed.")

輸出

Given list follows descending order.

方法 3:使用 reduce() 方法檢查降序排序列表的 Python 程式

匯入 functools 庫以使用 reduce() 函式。然後該函式定義了一個引數,用於遍歷列表。

演算法

  • 步驟 1 - 匯入 functools 以使用 reduce() 等函式。

  • 步驟 2 - 建立一個名為 is_descending() 的函式,其中包含一個引數 val。

  • 步驟 3 - reduce() 用於檢查當前元素是否小於下一個元素。

  • 步驟 4 - 建立名為 num_list 的列表,其中包含以某種順序排列的整數元素列表。

  • 步驟 5 - 基於條件,它檢查給定列表是否為降序。

示例

#the reduce function is imported
from functools import reduce

#is_descending function is defined with one argument as val
def is_descending(val):
   return reduce(lambda a, b: a > b and a or False, val) != False
    
#initializing the list with elements to check the order of the elements
num_list = [98, 45, 32, 12]
#using the if else loop the resultant statement is printed
if is_descending(num_list):
   print("Given list follows descending order.")
else:
   print("Descending order is not followed.")

輸出

Given list follows descending order.

結論

在本文中,我們使用了三種不同的方法來描述在 Python 語言中檢查降序排序列表的方式。對於這些,所有三種不同的方法都描繪了不同的方法。在第三種方法中使用 reduce() 方法,要遍歷列表的元素,我們需要檢視前一個元素是否大於後一個元素。

更新於: 2023-08-25

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告