How to select incrementing tuple list items?

I have the following list of tuples:

a = [(1, 2), (2, 4), (3, 1), (4, 4), (5, 2), (6, 8), (7, -1)]

I would like to select elements whose second value in the tuple increases compared to the previous one. For example, I would choose (2, 4)because it is 4superior 2, in the same way I would choose (4, 4)and (6, 8).

Can this be done in a more elegant way than a loop that starts explicitly with the second element?

To clarify, I want to select tuples for which the second element exceeds the second element of the previous tuple.

+4
source share
4 answers

You can use list comprehension to do this quite easily:

a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i-1][1]]

range(1, len(a)), , , , .

zip :

a = [two for one, two in zip(a, a[1:]) if two[1] > one[1]]
+1
>>> [right for left, right in pairwise(a) if right[1] > left[1]]
[(2, 4), (4, 4), (6, 8)]

pairwise - itertools, .

+2

You can use enumerateto get indexes and then to list:

a = [t[1] for t in enumerate(a[1:]) if t[1][1] > a[t[0]-1][1]]
0
source

You can use list comprehension

[i for i in a if (i[0] < i[1])]

Returns

[(1, 2), (2, 4), (6, 8)]

Edit: I was wrong in my understanding of the issue. The above code will return all tuples in which the second element is larger than the first. This is not the answer to the question that A. asked.

-1
source

All Articles