Skip to content

Instantly share code, notes, and snippets.

@claraj
Created January 28, 2018 18:59
Show Gist options
  • Save claraj/aeacc41e7f4fe954c4eaec7904d4a3e8 to your computer and use it in GitHub Desktop.
Save claraj/aeacc41e7f4fe954c4eaec7904d4a3e8 to your computer and use it in GitHub Desktop.
from book import Book # assume this exists, and Books have author and title fields
b1 = Book('jane Eyre', 'Charlotte Bronte', True, 1)
b2 = Book('The Handmaid\'s Tale', 'Margaret Atwood', True, 2)
b3 = Book('1984', 'George Orwell', True, 3)
booklist = [b1, b2, b2]
print(booklist)
# booklist.sort() sorts the original list in place
# sorted_list = booklist.sorted() returns a sorted list
# Provide a key parameter in the same way
# Sort by title. Note lowercase j in Jane Eyre so it's after Handmaid's Tail the end
booklist.sort(key=lambda b: b.title )
print('Sorted by title\n', booklist)
# Sort by title, case-insensitive, probably more useful in this case
# Need to define a function that takes the book as an arugment and returns
# some value that can be sorted - usually a string, number, date etc.
def lowertitle(b):
return b.title.lower()
booklist.sort(key=lowertitle)
print(booklist)
## Same but with lambda fn
booklist.sort(key= lambda b: b.title.lower())
# Sorted function works the same way, key parameter as before, but it returns a sorted list
sorted_books = sorted(booklist, key=lambda b:b.title.lower())
print('sorted books with sorted function\n', sorted_books)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment