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

更新於: 2020年5月13日

5K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.