在 Python 中检查列表是否已排序
列表是 Python 中使用最广泛的数据集合。我们可能会遇到需要知道给定列表是否已排序的情况。在本文中,我们将了解实现此目的的方法。
使用 sort
我们获取给定列表的副本,对其应用 sort 函数并将其副本存储为新列表。然后我们将其与原始列表进行比较,并检查它们是否相等。
示例
listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
listA_copy = listA[:]
# Apply sort to copy
listA_copy.sort()
if (listA == listA_copy):
print("Yes, List is sorted.")
else:
print("No, List is not sorted.")
# Checking again
listB = [11,23,21,51,67]
#Given list
print("Given list : ",listB)
listB_copy = listB[:]
# Apply sort to copy
listB_copy.sort()
if (listB == listB_copy):
print("Yes, List is sorted.")
else:
print("No, List is not sorted.")输出
运行以上代码将得到以下结果:
Given list : [11, 23, 42, 51, 67] Yes, List is sorted. Given list : [11, 23, 21, 51, 67] No, List is not sorted.
使用 all 和 range
我们可以使用 all 函数来检查列表的每个元素是否都小于其旁边的元素,并应用 range 函数遍历所有元素。
示例
listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
# Apply all and range
if (all(listA[i] <= listA[i + 1] for i in range(len(listA)-1))):
print("Yes, List is sorted.")
else:
print("No, List is not sorted.")
# Checking again
listB = [11,23,21,51,67]
print("Given list : ",listB)
# Apply all and range
if (all(listB[i] <= listB[i + 1] for i in range(len(listB)-1))):
print("Yes, List is sorted.")
else:
print("No, List is not sorted.")输出
运行以上代码将得到以下结果:
Given list : [11, 23, 42, 51, 67] Yes, List is sorted. Given list : [11, 23, 21, 51, 67] No, List is not sorted.
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP