在 Python 中检查列表是否已排序

pythonserver side programmingprogramming更新于 2025/12/26 1:16:17

列表是 Python 中最广泛使用的数据集合。我们可能会遇到需要知道给定列表是否已排序的情况。在本文中,我们将看到实现此目的的方法。

使用排序

我们获取给定列表的副本,对其应用排序函数,并将该副本存储为新列表。然后我们将其与原始列表进行比较,并检查它们是否相等。

示例

listA = [11,23,42,51,67]
# 给定列表
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.")

# 再次检查
listB = [11,23,21,51,67]
# 给定列表
print("Given list : ",listB)
listB_copy = listB[:]
# 对副本进行排序
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]
# 给定列表
print("Given list : ",listA)
# 应用 all 和 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.")
# 再次检查
listB = [11,23,21,51,67]
print("Given list : ",listB)
# 应用 all 和 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.

相关文章


有用资源