Dan Ru
Dan Ru

Reputation: 5

Comparison in list of tuples

list_a = [(0, 1, 2, 3, 4), (0, 1, 2, 4, 3), (0, 1, 3, 2, 4)]

I need a proper way to compare every single element of the tuples if they are greater than the other.

For example:

(0, 1, 2, 3, 4 )

Is 0 < 1 < 2 < 3 < 4 ?

It is not enough to find out if it's sorted. I need the explicit comparison of all elements.

Thanks in advance.

Upvotes: 0

Views: 101

Answers (2)

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22314

Your main concern here seems to be about how to iterate over consecutive pairs of elements in a sequence. The itertools recipes can be helpful here as they provide a neat way to iterate over those pairs.

Code for pairwise_comparisons

from itertools import tee

# From itertools recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

# Return pairwise comparison results
def pairwise_comparisons(seq):
    return [x < y for x, y in pairwise(seq)]

Example

list_a = [(0, 1, 2, 3, 4), (0, 1, 2, 4, 3), (0, 1, 3, 2, 4)]

for t in list_a:
    print(t, "comparisons:", pairwise_comparisons(t))

Output

(0, 1, 2, 3, 4) comparisons: [True, True, True, True]
(0, 1, 2, 4, 3) comparisons: [True, True, True, False]
(0, 1, 3, 2, 4) comparisons: [True, True, False, True]

Upvotes: 1

maede rayati
maede rayati

Reputation: 786

The following code will give you a list of list.

[[True if j>i[0] else False for j in i] for i in list_a]

This is comparison between the first item and all other items. If you want to compare adjacent values:

[[True if index >0 and j>i[index-1] else False for index,j in enumerate(i)] for i in list_a]

Upvotes: 0

Related Questions