在 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.")

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行以上代码将得到以下结果:

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.

更新于: 2020年5月13日

5K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告