Reputation: 5
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
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.
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)]
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))
(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
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