| Start |
|---|
| Make custom classes orderable
Though implementing all these methods would seem unnecessary, omitting some of them will make your code prone to bugs (opens new window). Examples:
But Sorting methods will raise a TypeError: unorderable types: IntegerContainer() < IntegerContainer()
Notice how the |
| Special case: dictionaries Getting the minimum or maximum or using To keep the dictionary structure, you have to iterate over the For By valueAgain this is possible using the |
| Using the key argument Finding the minimum/maximum of a sequence of sequences is possible: but if you want to sort by a specific element in each sequence use the |
| Default Argument to max, min You can't pass an empty sequence into ValueError: min() arg is an empty sequence However, with Python 3, you can pass in the keyword argument |
| Getting a sorted sequence Using one sequence: The result is always a new |
| Extracting N largest or N smallest items from an iterable To find some number (more than one) of largest or smallest values of an iterable, you can use the This is much more efficient than sorting the whole iterable and then slicing from the end or beginning. Internally these functions use the binary heap (opens new window) priority queue (opens new window) data structure, which is very efficient for this use case. Like Here is a program that extracts 1000 longest lines from a file: Here we open the file, and pass the file handle This only needs storage for a list of 1000 largest lines so far, which can be contrasted with which will have to hold the entire file in memory. |
Getting the minimum or maximum of several values |
| Minimum and Maximum of a sequence Getting the minimum of a sequence (iterable) is equivalent of accessing the first element of a The maximum is a bit more complicated, because But not if there are multiple elements that are evaluated as having the maximum value: Any iterable containing elements that support |
Read Article
https://develop.horje.com/learn/1434/reference