Created
January 28, 2018 18:59
-
-
Save claraj/aeacc41e7f4fe954c4eaec7904d4a3e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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