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() 方法,要遍历列表的元素,我们需要查看前一个元素是否大于后一个元素。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP