Python sorted() Function

Python 内置函数Python Built-in Functions


Description

sorted()The function performs a sorting operation on all iterable objects.

Difference between sort and sorted:

sort is a method applied to lists, while sorted can sort all iterable objects.

The sort method of a list operates on an existing list and has no return value, whereas the built-in function sorted returns a new list instead of modifying the original.

Syntax

sorted syntax:

sorted(iterable, cmp=None, key=None, reverse=False)

Parameter description:

  • iterable -- An iterable object.
  • cmp -- The comparison function. It has two parameters, both taken from the iterable. This function must follow the rule: return 1 if greater, -1 if less, 0 if equal.
  • key -- The element mainly used for comparison. It has only one parameter, which is taken from the iterable, and designates an element in the iterable to be used for sorting.
  • reverse -- Sorting rule. reverse = True means descending order, reverse = False means ascending order (default).

Return Value

Returns a re-sorted list.

Examples

The following example demonstrates how to use sorted:

>>>a = [5,7,6,3,4,1,2] >>> b = sorted(a) # Preserve the original list >>> a [5, 7, 6, 3, 4, 1, 2] >>> b [1, 2, 3, 4, 5, 6, 7] >>> L=[('b',2),('a',1),('c',3),('d',4)] >>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # Using the cmp function [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> sorted(L, key=lambda x:x[1]) # Using key [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(students, key=lambda s: s[2]) # Sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(students, key=lambda s: s[2], reverse=True) # Sort in descending order [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>>

Python 内置函数Python Built-in Functions

Other Extensions