【问题标题】:How to compare list of tuples? [duplicate]如何比较元组列表? [复制]
【发布时间】:2019-05-08 02:02:13
【问题描述】:

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

【问题讨论】:

  • 老实说,我不知道为什么人们如此渴望关闭重复的主题。我了解其他解决方案全面但明确地解决了 OP 的需求,OP 已经通过他自己的解决方案走上了正确的轨道。可能不像其他解决方案那样全面,但了解他的方法在哪些方面存在问题以及与建议的解决方案相比它缺乏什么是学习的重要部分
  • 感谢理解。我想我不知道“单调地”搜索答案的正确方法。提供的函数列表肯定会帮助我编写脚本。看来我也需要了解有关 zip 功能的更多信息。
  • @kerwei,我认为这就是为什么在将问题标记为重复后评论部分仍然打开的原因。这样人们就可以围绕已经在 Stackoverflow 上的其他地方找到经过测试且具有弹性的解决方案的问题进行讨论。

标签: python python-3.x


【解决方案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

【讨论】:

  • 谢谢。我不知道如何寻找答案,“单调”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2015-08-01
  • 2012-11-25
  • 2017-09-01
相关资源
最近更新 更多