檢查Python列表是否嚴格遞增
給定一個列表,我們可能需要檢查其元素的序列。在這篇文章中,我們將找出列表中是否存在元素以嚴格遞增的順序排列。下面的程式實現了這個目標。
使用all和zip
在這種方法中,我們首先切片每個元素,將其值與其切片後的下一個元素進行比較。如果所有這些比較都成立,那麼我們就得出結論:該列表嚴格按照遞增順序排列。
示例
listA = [11,23,42,51,67] #Given list print("Given list : ",listA) # Apply all and range if (all(i < j for i, j in zip(listA, 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(i < j for i, j in zip(listB, 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.
使用itertools.starmap
這建立了一個迭代器,它使用從可迭代物件中獲得的引數來計算函式。我們將列表中的元素逐個切片後進行zip壓縮,然後使用小於等於運算子進行處理。請注意,我們在下面的示例中使用了字串而不是數字。
示例
import operator import itertools listA = ['Mon','Tue','Sun'] #Given list print("Given list : ",listA) # Apply all and range if all(itertools.starmap(operator.le, zip(listA, listA[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.") # Checking again listB = ['Mon','Sun','Tue'] print("Given list : ",listB) # Apply all and range if all(itertools.starmap(operator.le, zip(listB, listB[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.")
輸出
執行以上程式碼,我們得到以下結果:
Given list : ['Mon', 'Tue', 'Sun'] No, List is not sorted. Given list : ['Mon', 'Sun', 'Tue'] Yes, List is sorted.
廣告