检查列表是否在Python中排序
列表是python中使用最广泛的数据收集器。当我们需要知道给定列表是否已排序时,我们可能会遇到这种情况。在本文中,我们将看到实现这一目标的方法。
与排序
我们获取给定列表的副本,对其应用排序功能,然后将该副本存储为新列表。然后,我们将其与原始列表进行比较,并检查它们是否相等。
示例
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函数遍历所有元素。
示例
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.