The most "pythonic" way to check the list subscription order?

What is the most "pythonic" way to calculate if a list list has each item larger 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 larger list) is larger than the 2nd element. So, for the first element its false, because 3.1 <3,13. 2nd and 3rd positions are correct.

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

+4
source share
3 answers

Pattern matching and list comprehension:

 [x > y for x, y in a] 
+8
source

This will return a list of booleans:

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

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

 all([x[0] > x[1] for x in a]) 
+4
source
 >>> from operator import ge >>> from itertools import starmap >>> a = [[3.1, 3.13], [3.14, 3.12], [3.12, 3.1]] >>> list(starmap(ge, a)) [False, True, True] 

or if you do not want to import starmap

 >>> map(ge, *zip(*a)) [False, True, True] 
+3
source

Source: https://habr.com/ru/post/1501995/


All Articles