检查列表单调性的有效和pythonic方法是什么?
即它具有单调增加或减少的值?
例子:
[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
Run Code Online (Sandbox Code Playgroud) 我试图找出一个整数列表是连贯的还是"在一个范围内",这意味着两个相邻元素之间的差异必须是一个,并且数字必须单调递增.我找到了一个简洁的方法,我们可以按列表中的数字减去列表中元素的位置进行分组 - 当数字不连贯时,这种差异会发生变化.显然,当序列不包含间隙或重复时,应该只有一个组.
测试:
>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [1, 2, 3, 4, 5, 7]
>>> l3 = [1, 2, 3, 4, 5, 5]
>>> l4 = [1, 2, 3, 4, 5, 4]
>>> l5 = [6, 5, 4, 3, 2, 1]
>>> def is_coherent(seq):
... return len(list(g for _, g in itertools.groupby(enumerate(seq), lambda (i,e): i-e))) == 1
...
>>> is_coherent(l1)
True
>>> is_coherent(l2)
False
>>> is_coherent(l3)
False
>>> is_coherent(l4)
False …Run Code Online (Sandbox Code Playgroud)