Python:Sorting an Array

From Progzoo
Jump to navigation Jump to search

Sort a list in place

The method sort can be used:

Sort the list 2,7,5,4.

[Font] [Default] [Show] [Resize] [History] [Profile]

Create a new sorted list

The function sorted can be used:

Return a new list of the values 2,7,5,4 without modifying the original list.

[Font] [Default] [Show] [Resize] [History] [Profile]

Sort a list in reverse

Sort the list 2,7,5,4 in reverse.

[Font] [Default] [Show] [Resize] [History] [Profile]

Sort a list using a custom key function

A key can be associated with each item in the list to specify how they are to be sorted. The list is sorted according to the order of the keys, not the original values. You provide a key function, which maps each element to its key.

For example, to sort a list by order of increasing string length:

[Font] [Default] [Show] [Resize] [History] [Profile]

Sort a list using a custom comparator

In Python 2.x, you can create your own comparator. This mens that you decide how the sort is to be done.

Warning: this feature has been removed in Python 3.x because it is less efficient then using keys, so it should not be used in new code.

You must implement a function that returns a negative, zero or a positive integer depending on how the first argument (let's call o1) compares to the second argument (let's call o2).

return -1 (or any negative number) if o1 comes before o2
return  0 if o1 and o2 are the same
return  1 (or any positive number) if o1 comes after o2

[Font] [Default] [Show] [Resize] [History] [Profile]