![]() Movies = sorted(movies, key=movie_key, reverse=True) It is just a shorthand for: def movie_key(movie): Lambdas really shine when we need to supply a simple function as a parameter to another function, such as supplying a function as a key parameter to sorted.īack to our sorting example, when we write: movies = sorted(movies, key=lambda movie: movie, reverse=True) The lambda keyword allows us to declare small, anonymous, single-line functions, taking one or more parameters and returning a value of an expression. A really simple concept with a fancy name, lambda functions or simply lambdas are a syntactic sugar in Python. ![]() The key thing to unpack here is key=lambda movie: movie - what exactly is going on here? Lambda functions - what are they?įirst we need to understand what a lambda is. This will get us the following ordering of movies (note the descending ordering of ratings) (1994, 'The Shawshank Redemption', 9.2) movies = sorted(movies, key=lambda movie: movie, reverse=True) ![]() Let's use this knowledge to sort our movies by rating, in descending order. The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. The official Python docs explain this in simple terms: Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons. Python's sorted function offers a simple solution - use the key parameter. In our previous example, what if we wanted to sort the movies by rating first, then by year? ![]() Understanding how lists of tuples or lists of lists are sorted is crucial to understanding more complex sorting patterns - those using the key parameter. Note that sorted always sorts in ascending order unless we modify its behaviour using key or reverse parameters. movie - title, lexicographically (case sensitive), ascending.In our movie example, this means that the movies get sorted by comparing: In case of a tie, the tuples are then sorted by comparing the second element, then the third, and so on. The tuples get sorted by first comparing their elements at position 0, in this case the year. Let's say we have a list of movies with their ratings and year of release: movies = [Ĭalling sorted(movies) returns the following list: (1972, 'The Godfather', 9.2) In order to understand how sorting by key works in the background, let's first see how sorted works when sorting lists of lists (or tuples). # Sort by population densityĬities = sorted(cities, key=lambda city: (city / city)) # Sort by country, then by nameĬities = sorted(cities, key=lambda city: (city, city))Ī nice trick with key function is that we can provide an arbitrary function that accepts an object to be sorted, for example we can calculate population density on the fly. As tuples are sorted by comparing them field by field, this will effectively sort our cities by country, then by name. Here, for each city we'll provide a tuple (country, name) to the sorting function. Sort alphabetically by country, then by name # Sort by populationĬities = sorted(cities, key=lambda city: city)Ī very common pattern is to reverse the sorting order by using negative value of the sorting key (note the minus sign in front of city) # Sort by population DESCENDINGĬities = sorted(cities, key=lambda city: -city)Ģ. This means that each city will be compared against other cities by looking only at their population field. We'll tell sorted that for each city, we want it to take population as the sorting key. Here's how we'd do this for our examples: We'll need to explicitly tell the sorted method how we want to sort our objects. What do you think happens if we just call sorted(dicts)? How will the sorted function know which field(s) of our cities to use for sorting? If there are cities from the same country order them alphabetically by nameįor the sake of example let's represent cities as simple Python dicts: cities = [ We'd like to sort the list in various ways: Let's say we have a list of city names along with their country, population and area. Sorting complex objects using a lambda key function Here's an example: A = # An unsorted array of integersī = sorted(A) # sorted(A) returns a sorted copy of A It returns a sorted list of elements of that object. You'll pass a list, dict, set or any other kind of iterable object to the built-in function sorted.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |