📌  相关文章
📜  Python – 测试严格递减列表

📅  最后修改于: 2022-05-13 01:54:37.531000             🧑  作者: Mango

Python – 测试严格递减列表

单调序列测试是一种实用程序,在数学中具有多种应用,因此在与数学相关的每个领域中都有应用。由于数学和计算机科学通常是并行的,因此数学运算(例如检查严格递减序列)对于收集知识很有用。让我们讨论执行此测试的某些方法。

方法#1:使用all() + zip()
all() 通常检查提供给它的所有元素。 zip() 的任务是从头开始链接列表和从第一个元素开始的列表,以便可以对所有元素执行检查。

# Python 3 code to demonstrate 
# Test for strictly decreasing list
# using zip() + all()
  
# initializing list
test_list = [10, 8, 7, 5, 4, 1]
  
# printing original lists
print ("Original list : " + str(test_list))
  
# using zip() + all()
# Test for strictly decreasing list
res = all(i > j for i, j in zip(test_list, test_list[1:]))
  
# printing result
print ("Is list strictly decreasing ? : " + str(res))
输出 :
Original list : [10, 8, 7, 5, 4, 1]
Is list strictly decreasing ? : True

方法 #2:使用reduce() + lambda
与 lambda 结合的 reduce() 也可以执行检查单调性的任务。 reduce函数用于将结果累积为 True 或 False,lambda函数检查每个索引值与下一个索引值。

# Python 3 code to demonstrate 
# Test for strictly decreasing list
# using reduce() + lambda
  
# initializing list
test_list = [10, 8, 7, 5, 4, 1]
  
# printing original lists
print ("Original list : " + str(test_list))
  
# using reduce() + lambda
# Test for strictly decreasing list
res = bool(lambda test_list: reduce(lambda i, j: j if i > j else 9999, test_list) != 9999)
  
# printing result
print ("Is list strictly decreasing ? : " + str(res))
输出 :
Original list : [10, 8, 7, 5, 4, 1]
Is list strictly decreasing ? : True