![]() ![]() This courseware module is offered as part of the Repository of Open and Affordable Materials at Penn State.Įxcept where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Dutton e-Education Institute, College of Earth and Mineral Sciences, The Pennsylvania State University Dutton e-Education Institute, College of Earth and Mineral Sciences, The Pennsylvania State UniversityĪndrew Murdoch, John A. ![]() The heapq module of the Python standard library implements an algorithm for realizing a priority queue in a Python list and we are going to discuss it in the final part of this section.Īuthors and/or Instructors: James O'Brien, John A. An example of such a data structure is the so-called priority queue or heap. This can save a lot of time compared to frequently re-sorting the collection. always the element with the lowest value for a certain attribute), it is advantageous to use a specialized data structure that keeps the collection sorted whenever an element is added or removed. Therefore, if you mainly need to access the elements in a collection in a specific order based on their properties (e.g. ![]() Sorting can be a somewhat time-consuming operation for larger collections. For instance, the following example uses a lambda expression for the ‘key’ parameter to sort the names from l2 based on their length (in descending order) rather than based on their lexicographical order: print( sorted(l2, reverse = True, key = lambda x: len(x)) ) Output: In addition, we can use the keyword argument ‘key’ to provide a function that will be applied to the elements and they will then be sorted based on the values returned by this function. The keyword argument ‘reverse’ can be used to sort the elements in descending order instead: print( sorted(l2, reverse = True) ) Output: When we define our own classes (Section 4.6) and want to be able to sort objects of a class based on their properties, we have to define the < operator in a suitable way in the class definition. This means numbers are sorted in increasing order and strings are sorted in lexicographical order. Sorted(…) and sort() by default sort the elements in ascending order based on the < comparison operator. If our collection is a list, we can also use the list method sort() instead of the function sorted(…), e.g. Python provides a function sorted(…) to sort the elements in a collection that allows for iterating over the elements (e.g. One common operation on collections is sorting the elements in a collection. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |