1

I'm trying to compare the second value in a list of tuples with the next second value and so on and so forth and return true every value is greater than the next. For example...

If each preceding value is greater than the next one, it would return 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)]

If not then return 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)]

I've tried the following and I feel like I'm on the right track but cannot wrap my head around it.

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])
r6danl99
  • 89
  • 2
  • 7
  • Honestly, I'm not sure why people are so eager to close off topics as duplicate. I understand that the other solution addresses the OP's needs comprehensively but clearly, the OP is already on the right track with his own solution. May not be as comprehensive as the other solution, but understanding where his approach is off and what it lacks compared to the proposed solution is an important part of learning – kerwei May 08 '19 at 02:23
  • Thanks for understanding. I suppose I didn't know the proper way to search for my answer, "monotonically". The list of functions provided will definitely aid in my scripting. It also looks as though I need to learn more about the zip function as well. – r6danl99 May 08 '19 at 02:34
  • @kerwei, I think that is why the comment section is still open after a question is marked as duplicate. So that people can discuss around the problem which has already found a tested and resilient solution somewhere else on Stackoverflow. – ggrelet May 08 '19 at 06:28

1 Answers1

1

Use this set of function, they are really useful to test monotony of list values:

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

And then isolate your list of second element of the tuples:

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)

Result:

True
ggrelet
  • 1,071
  • 7
  • 22