3

I have an list of list, list = [(1,2,5), (2,8,7),(3,6,9)], and I want to find the biggest number of the third column, so I tried:

zipped = zip(*list)
print max(zipped[2])

But it does not show the biggest number. Anyone know why and a solution?

martineau
  • 119,623
  • 25
  • 170
  • 301
trivial
  • 141
  • 2
  • 8

2 Answers2

13

Works on all newer Pythons:

>>> li = [(1,2,5), (2,8,7),(3,6,9)]
>>> max(l[2] for l in li)
9

If you have text:

>>> li = [('1','2','5'), ('2','8','7'),('3','6','9')]
>>> max(int(l[2]) for l in li)
9

And works even if the source is an iterator / generator. This is on Py3.3 where zip returns an iterator:

>>> gli=(e for e in li)
>>> max(int(l[2]) for l in gli)
9
>>> max(int(l[2]) for l in zip(*li))
9
the wolf
  • 34,510
  • 13
  • 53
  • 71
  • Wow ... I have no idea why I didn't write it this way ... (+1) ... I can console myself that it nicely allows OP to get the full tuple with the biggest 3rd item ... But if you just need the item, this is definitely cleaner. – mgilson Feb 14 '13 at 21:28
4

Works for me on python2.7.

>>> l = [(1,2,5),(2,8,7),(3,6,9)]
>>> zip(*l)
[(1, 2, 3), (2, 8, 6), (5, 7, 9)]
>>> max(zip(*l)[2])
9

Another option:

max(l,key=lambda x:x[2])[2]

or if you prefer itemgetter:

from operator import itemgetter
max(l,key=itemgetter(2))[2]

This is probably more efficient in terms of memory and it'll work on python3.x where zip no longer returns a list.

The key here is that it allows you to get the full tuple that is the biggest (biggest determined by the 3rd element) and then you just pull the correct element out of there if you want it.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Maybe OP's using Py3k and zip returns an iterator – JBernardo Feb 14 '13 at 21:24
  • @JBernardo -- Yeah. I just thought of that as well... That's why I added that my second version will work on python3.x as well. – mgilson Feb 14 '13 at 21:24
  • sorry, I find the reason, my list is a list of text and the example I give is a list of number...would you please tell me how to change it? – trivial Feb 14 '13 at 21:27
  • @trivial -- `map(int,iterable_of_string)` will return a new list with the strings converted to integers (if possible) – mgilson Feb 14 '13 at 21:29