Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, May 4, 2012

max method explained

One nice thing about the max function is that you can provide a key that points to a function which basically extracts the value from the elements on which we want max to order the elements.
person1 = {}
person1['name'] = 'Valerie'
person1['age'] = 5

person2 = {}
person2['name'] = 'Robby'
person2['age'] = 35

person3 = {}
person3['name'] = 'Lindsey'
person3['age'] = 9

persons = [person1, person2, person3]

#goal find the eldest person
def getAge(person):
    return person['age']

print max(persons, key=getAge)

{'age': 35, 'name': 'Robby'}

No comments:

Post a Comment