python - 如何比较元组列表?

标签 python python-3.x

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

SOURCE: 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/

相关文章:

django - 如何在 django 中发送多个查询集?

python - 如何从 Python 在 Gnome 中安全地清除两个剪贴板?

Python:将 'days since 1990' 转换为日期时间对象

python - 如何在python中编写和保存html文件?

python - Airflow 无法导入自定义 python 包

python-3.x - 使用 statsmodels.tsa.grangercausalitytests 进行简单格兰杰因果检验

python - 具有重复组的正则表达式

python - 将整数从一个 def 编辑到另一个

python - QPlainTextEdit 和 QCompleter 焦点问题

python-3.x - mypy可以根据当前对象的类型选择方法返回类型吗?