4

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
dorothy
  • 1,213
  • 5
  • 20
  • 35
  • do not overvalue "pythonic" way of doing things in python. To keep code clean is much more important. Evidently you can use "pythonic" map function with simple lambda for this task, but in this way your code won't be much clean. Keep the things simple for understanding, do not avoid for loops if it is natural to use them. – Alexander Smirnov Sep 13 '13 at 06:27
  • 1
    It is not natural to use stacked loop if you can use list comprehension which is a powerful and easily readable pythonic tool. In this particular case at least. – sashkello Sep 13 '13 at 06:29
  • 1
    @AlexanderSmirnov Pythonic *is* clean and simple! Never mistake Pythonic to mean complex, because when you gain unnecessarily complex, because when you gain complexity, you lose Pythonicity. – kqr Sep 13 '13 at 07:36
  • kqr, sashkello I agree with you. I like list comprehension solution for this task. – Alexander Smirnov Sep 13 '13 at 08:21

3 Answers3

8

Pattern matching and list comprehension:

[x > y for x, y in a]
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
4

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])
sashkello
  • 17,306
  • 24
  • 81
  • 109
  • Not that it really matters, but one can omit the brackets in the all version in one wants. (apologies to SetMMorton) – Thomas Sep 13 '13 at 07:11
  • @Thomas Yeah, you can, I find it a bit harder to read though personally as it is not immediately subconsciously associated with a list, which it is. – sashkello Sep 13 '13 at 07:13
3
>>> 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 don't want to import starmap

>>> map(ge, *zip(*a))
[False, True, True]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502