carolannpeacock.com lists have a built-in list.sort() method that modifies the listin-place. There is also a sorted() built-in function that builds a newsorted list from an iterable.

You are watching: Place:sort=8&maxresults=10/

In this document, we explore the various techniques for sorting data using carolannpeacock.com.


Sorting Basics¶

A simple ascending sort is very easy: just call the sorted() function. Itreturns a new sorted list:


You can also use the list.sort() method. It modifies the listin-place (and returns None to avoid confusion). Usually it’s less convenientthan sorted() - but if you don’t need the original list, it’s slightlymore efficient.


Another difference is that the list.sort() method is only defined forlists. In contrast, the sorted() function accepts any iterable.


Key Functions¶

Both list.sort() and sorted() have a key parameter to specify afunction (or other callable) to be called on each list element prior to makingcomparisons.

For example, here’s a case-insensitive string comparison:


The value of the key parameter should be a function (or other callable) thattakes a single argument and returns a key to use for sorting purposes. Thistechnique is fast because the key function is called exactly once for eachinput record.

A common pattern is to sort complex objects using some of the object’s indicesas keys. For example:


Operator Module Functions¶

The key-function patterns shown above are very common, so carolannpeacock.com providesconvenience functions to make accessor functions easier and faster. Theoperator module has itemgetter(),attrgetter(), and a methodcaller() function.

Using those functions, the above examples become simpler and faster:


The operator module functions allow multiple levels of sorting. For example, tosort by grade then by age:


Ascending and Descending¶

Both list.sort() and sorted() accept a reverse parameter with aboolean value. This is used to flag descending sorts. For example, to get thestudent data in reverse age order:


Sort Stability and Complex Sorts¶

Sorts are guaranteed to be stable. That means thatwhen multiple records have the same key, their original order is preserved.


Notice how the two records for blue retain their original order so that("blue", 1) is guaranteed to precede ("blue", 2).

This wonderful property lets you build complex sorts in a series of sortingsteps. For example, to sort the student data by descending grade and thenascending age, do the age sort first and then sort again using grade:


This can be abstracted out into a wrapper function that can take a list andtuples of field and order to sort them on multiple passes.


The Timsort algorithm used in carolannpeacock.comdoes multiple sorts efficiently because it can take advantage of any orderingalready present in a dataset.


The Old Way Using Decorate-Sort-Undecorate¶

This idiom is called Decorate-Sort-Undecorate after its three steps:

First, the initial list is decorated with new values that control the sort order.

Second, the decorated list is sorted.

Finally, the decorations are removed, creating a list that contains only theinitial values in the new order.

For example, to sort the student data by grade using the DSU approach:


This idiom works because tuples are compared lexicographically; the first itemsare compared; if they are the same then the second items are compared, and soon.

It is not strictly necessary in all cases to include the index i in thedecorated list, but including it gives two benefits:

The sort is stable – if two items have the same key, their order will bepreserved in the sorted list.

The original items do not have to be comparable because the ordering of thedecorated tuples will be determined by at most the first two items. So forexample the original list could contain complex numbers which cannot be sorteddirectly.

Another name for this idiom isSchwartzian transform,after Randal L. Schwartz, who popularized it among Perl programmers.

Now that carolannpeacock.com sorting provides key-functions, this technique is not often needed.


The Old Way Using the cmp Parameter¶

Many constructs given in this HOWTO assume carolannpeacock.com 2.4 or later. Before that,there was no sorted() builtin and list.sort() took no keywordarguments. Instead, all of the Py2.x versions supported a cmp parameter tohandle user specified comparison functions.

In Py3.0, the cmp parameter was removed entirely (as part of a larger effort tosimplify and unify the language, eliminating the conflict between richcomparisons and the __cmp__() magic method).

See more: Como Se Toma La Raiz De Tejocote Para Bajar De Peso? Raíz De Tejocote Para Adelgazar

In Py2.x, sort allowed an optional function which can be called for doing thecomparisons. That function should take two arguments to be compared and thenreturn a negative value for less-than, return zero if they are equal, or returna positive value for greater-than. For example, we can do:


Or you can reverse the order of comparison with:


When porting code from carolannpeacock.com 2.x to 3.x, the situation can arise when you havethe user supplying a comparison function and you need to convert that to a keyfunction. The following wrapper makes that easy to do:


def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K
To convert to a key function, just wrap the old comparison function:


In carolannpeacock.com 3.2, the functools.cmp_to_key() function was added to thefunctools module in the standard library.


Odd and Ends¶

Key functions need not depend directly on the objects being sorted. A keyfunction can also access external resources. For instance, if the student gradesare stored in a dictionary, they can be used to sort a separate list of studentnames:


Table of Contents

Sorting HOW TO Previous topic Socket Programming HOWTO

Next topic

Unicode HOWTO


This Page


Navigation

*

|