Python-如何检查列表的单调性


问题内容

什么是检查列表单调性的 有效且Python 方式?
即它具有单调增加或减少的值?

例子:

[0, 1, 2, 3, 3, 4]   # This is a monotonically increasing list
[4.3, 4.2, 4.2, -2]  # This is a monotonically decreasing list
[2, 3, 1]            # This is neither

问题答案:

最好避免使用诸如“增加”或“减少”之类的模棱两可的术语,因为不清楚是否接受平等。您应该始终使用例如“不增加”(显然接受平等)或“严格减少”(显然不接受平等)。

def strictly_increasing(L):
    return all(x<y for x, y in zip(L, L[1:]))

def strictly_decreasing(L):
    return all(x>y for x, y in zip(L, L[1:]))

def non_increasing(L):
    return all(x>=y for x, y in zip(L, L[1:]))

def non_decreasing(L):
    return all(x<=y for x, y in zip(L, L[1:]))

def monotonic(L):
    return non_increasing(L) or non_decreasing(L)