首页 > 解决方案 > 如何比较元组列表?

问题描述

我正在尝试将元组列表中的第二个值与下一个第二个值进行比较,依此类推,然后返回 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])

标签: pythonpython-3.x

解决方案


使用这组函数,它们对于测试列表值的单调性非常有用:

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

推荐阅读