This question already has answers here:
Python - How to check list monotonicity
                                
                                    (11个答案)
                                
                        
                                在10个月前关闭。
            
                    
我试图将元组列表中的第二个值与下一个第二个值进行比较,依此类推,以此类推,并返回true,每个值都大于下一个。例如...

如果每个前面的值都大于下一个,则它将返回True。

968854000 > 957946000 > 878825000 > 810870000 = True
list_of_tuples = [
 ('2018-09-30', 968854000),
 ('2017-09-30', 957946000),
 ('2016-09-30', 878825000),
 ('2015-09-30', 810870000)]


如果不是,则返回False。

968854000 > 957946000 !> 998825000 stop evaluation and return False
list_of_tuples = [
 ('2018-09-30', 968854000),
 ('2017-09-30', 957946000),
 ('2016-09-30', 998825000),
 ('2015-09-30', 810870000)]


我已经尝试了以下方法,但我感觉自己处在正确的轨道上,但无法将其包裹住。

for i, j in enumerate(list_of_tuples):
    date = j[0]
    value = j[1]
    if value > list_of_tuples[i+1][1]:
        print(list_of_tuples[i+1][1])

最佳答案

使用此功能集,它们对于测试列表值的单调性非常有用:

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)



  消息来源:https://stackoverflow.com/a/4983359/4949074


然后隔离出元组的第二个元素列表:

list_of_tuples = [
 ('2018-09-30', 968854000),
 ('2017-09-30', 957946000),
 ('2016-09-30', 878825000),
 ('2015-09-30', 810870000)]

list_to_test = [x[1] for x in list_of_tuples]

non_increasing(list_to_test)


结果:

True

关于python - 如何比较元组列表? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56032561/

10-10 11:55
查看更多