检查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.")

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.

使用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.

更新于:2020年5月13日

1000+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告