# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
# code for loading the format for the notebook
import os

# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir('../notebook_format')
from formats import load_style
load_style()
# -

os.chdir(path)

# # A quick note on *itemgetter*, *attrgetter*
#
#
# By using the key argument with the `sorted` function we can accomplish a bit more complex things when it comes to sorting. Note that key only accepts functions as its parameters, thus in the following we use a lambda to sort by the second element of the tuples.

# +
students = [  
    ( 'john', 'A', 15 ),  
    ( 'jane', 'B', 12 ),  
    ( 'dave', 'B', 10 ),  
]

# sort by age 
sorted( students, key = lambda x : x[2] ) 
# -

# Instead of doing that we can use the `itemgetter` for convenience.

from operator import itemgetter
sorted( students, key = itemgetter(2) )


# Applying the notion to a class object.

# +
class Student(object):  
    def __init__( self, name, grade, age ):  
        self.name = name  
        self.grade = grade  
        self.age = age  
    def __repr__(self):  
        return repr( ( self.name, self.grade, self.age ) )  

student_objects = [  
    Student( 'john', 'A', 15 ),  
    Student( 'jane', 'B', 12 ),  
    Student( 'dave', 'B', 10 ),  
] 
# -

# Write your own lambda way.

sorted( student_objects, key = lambda student: student.age )

# Using `attrgetter`.

# +
from operator import attrgetter

# sort by grade then age
sorted( student_objects, key = attrgetter( 'grade', 'age' ) ) 

StarcoderdataJupyterScriptsDedupFiltered