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?
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?
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
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.