3

I create a list filled with named tuples:

from collections import namedtuple
Point = namedtuple('Point', 'x y')
a = Point(5,4)
b = Point(8,3)
tab = [a,b]

print tab
>>[Point(x=5, y=4), Point(x=8, y=3)]

I would like to have the max of the x values in the list 'tab'

max(tab.x)
>> 8
Jon
  • 55
  • 8

2 Answers2

5

Try like this,

>>> max(tab, key=lambda k: k.x)
Point(x=8, y=3)
>>> max(tab, key=lambda k: k.x).x
8

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).

https://docs.python.org/2/library/functions.html#max

Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
2

You may simple do it as :

print max([i.x for i in tab])

However it may not be the best approach to do the same.

ZdaR
  • 22,343
  • 7
  • 66
  • 87