Merge sort thả lists have sầu a built-in list.sort() method that modifies the listin-place. There is also a sorted() built-in function that builds a newsorted danh mục from an iterable.

Bạn đang xem: Merge sort

In this document, we explore the various techniques for sorting data using Pykhiêm tốn.

Sorting Basics¶

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

You can also use the menu.sort() method. It modifies the listin-place (và returns None khổng lồ 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 các mục.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 lớn specify afunction (or other callable) to be called on each danh sách element prior to lớn 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 và returns a key lớn use for sorting purposes. Thistechnique is fast because the key function is called exactly once for eachđầu vào record.

A comtháng pattern is to lớn 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 providesconvenience functions to lớn make accessor functions easier and faster. Theoperator module has itemgetter(),attrgetter(), và 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 & Descending¶

Both menu.sort() & sorted() accept a reverse parameter with aboolean value. This is used lớn flag descending sorts. For example, lớn get thestudent data in reverse age order:

Sort Stability & Complex Sorts¶

Sorts are guaranteed to be stable. That means thatwhen multiple records have sầu 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 khổng lồ precede ("blue", 2).

This wonderful property lets you build complex sorts in a series of sortingsteps. For example, khổng lồ sort the student data by descending grade & thenascending age, do the age sort first và then sort again using grade:

This can be abstracted out into a wrapper function that can take a các mục andtuples of field and order to lớn sort them on multiple passes.

The Timsort algorithm used in wpuonline.comdoes multiple sorts efficiently because it can take advantage of any orderingalready present in a dataphối.

Xem thêm: Lưu Trữ Top 19 Giao Diện Web Bán Hàng Đơn Giản, Miễn Phí Hot Nhất 2020

The Old Way Using Decorate-Sort-Undecorate¶

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

First, the initial danh mục is decorated with new values that control the sort order.

Second, the decorated danh sách is sorted.

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

For example, khổng lồ 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 lớn include the index i in thedecorated các mục, but including it gives two benefits:

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

The original items vày not have to lớn be comparable because the ordering of thedecorated tuples will be determined by at most the first two items. So forexample the original danh sách could contain complex numbers which cannot be sorteddirectly.

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

Now that Pyhạn hẹp sorting provides key-functions, this technique is not often needed.

The Old Way Using the cmp Parameter¶

Many constructs given in this HOWTO assume Pynhỏ 2.4 or later. Before that,there was no sorted() builtin và 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 & unify the language, eliminating the conflict between richcomparisons & the __cmp__() magic method).

Xem thêm: Phòng Pr Nội Bộ Là Gì ? Vai Trò Của Pr Nội Bộ Chuyên Đề: Pr Nội Bộ

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

Or you can reverse the order of comparison with:

When porting code from Pybé 2.x to lớn 3.x, the situation can arise when you havethe user supplying a comparison function và you need to convert that khổng lồ a keyfunction. The following wrapper makes that easy to do:

def cmp_to_key(mycmp): 'Convert a cmp= function into lớn 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 lớn a key function, just wrap the old comparison function:

In 3.2, the functools.cmp_to_key() function was added khổng lồ thefunctools module in the standard library.

Odd and Ends¶

Key functions need not depkết thúc 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 lớn sort a separate các mục of studentnames:

Table of Contents

Sorting HOW TO Previous topic Socket Programming HOWTO

Next topic

Unicode HOWTO

This Page




Chuyên mục: Tin tức