Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most "pythonic" way to check ordering of sub lists of a list?

Tags:

python

what's the most "pythonic" way to calculate if a list of list has each element greater than its neigbbour? eg

a = [[3.1, 3.13], [3.14, 3.12], [3.12, 3.1]] 

I want to see if the first element in each of the list (inside the bigger list) is greater than the 2nd element. So for first item, its false because 3.1 < 3.13. 2nd and 3rd item is true.

I can most certainly use a for loop, but would like to see alternative approaches. thanks.

like image 268
dorothy Avatar asked Dec 07 '22 05:12

dorothy


2 Answers

Pattern matching and list comprehension:

[x > y for x, y in a]
like image 105
Emil Vikström Avatar answered Dec 08 '22 17:12

Emil Vikström


This will return a list of boolean values:

[x[0] > x[1] for x in a]

If you want to return True if all values are True and False otherwise:

all([x[0] > x[1] for x in a])
like image 39
sashkello Avatar answered Dec 08 '22 18:12

sashkello