Python – 检查降序排序的列表
List 是Python语言中的一种数据结构,可以在这对“[]”括号中存储不同数据类型的元素。数据可以按升序或降序进行排序。在列表中,如果前一个元素大于后一个元素,则按降序排序,反之,则按升序排序。通过三种不同的方法,可以验证Python中降序排序的列表。
方法
方法1 – 使用迭代方法
方法2 – 使用sort()函数
方法3 – 使用reduce()方法
方法1:使用迭代方法检查降序排序的Python程序
该函数定义了一个参数,用于检查列表。为了检查列表的元素,我们需要查看前一个元素是否大于后一个元素。使用for循环遍历num_list,当满足条件时,它遵循降序排序,否则就不是。num_list初始化为一列元素。
算法
- 步骤1 - 定义带有一个参数val的函数。
-
步骤2 - 使用for循环遍历列表的元素范围。
-
步骤3 - 为了找出降序,值”a”应该小于下一个元素。
-
步骤4 - 根据条件,检查给定的列表是否为降序排列。
示例
#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.
方法二:使用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.
第三种方法:使用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()方法来遍历列表的元素,需要查看前一个元素是否大于即将到来的元素。